我对 Twig 模板和 Drupal 8 比较陌生,在循环遍历节点模板文件中的某些字段时遇到了一些麻烦。基本上,我的日期字段限制为最多 2 个字段,如果输入 2 个字段,我希望将它们显示为日期范围,而不仅仅是页面上的两个随机日期。
我试图通过使用 for 循环/if 语句来检查是否存在多个字段,并相应地显示字段输出来实现这一目标。
这是我到目前为止所拥有的:
{% set dateLength = "" %}
{% for date in content.field_date['#items'].getValue() %}
{% set dateLength %}
{{ loop.length }}
{% endset %}
{% endfor %}
{% if dateLength == 2 %}
{{ content.field_date['#items'].getValue()|last.value }}—{{ content.field_date['#items'].getValue()|first.value }}
{% else %}
{{ content.field_date['#items'].getValue() }}
{% endif %}
请告诉我我是否想得太多了。任何指示将不胜感激。感谢您的帮助。
标记。
最佳答案
我建议您使用 length twig filter 来计算 dateLength 变量如下:
{% set dateLength = content.field_date['#items'].getValue() | length %}
希望这有帮助
关于loops - Drupal 8 中的循环字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38216373/