2

I'm kind of new to Twig templating and Drupal 8 and I'm having a bit of trouble looping through some fields in a node template file. Basically, I have a Date field limited to a maximum of 2 fields, and if 2 fields are entered, I would like to display them like a date range and not just two random dates plonked on a page.

I'm trying to achieve this by using a for loop/if statement to check if more than one field exists, and display the field output accordingly.

Here's what I have so far:

  {% 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 %}

Let me know if I'm overthinking this. Any pointers would be much appreciated. Thanks for your help.

Mark.

m918273
  • 110
  • 2
  • 11

1 Answers1

2

I suggest you to calculate the dateLength variable with the length twig filter as follow:

{% set dateLength  = content.field_date['#items'].getValue() | length %}

Hope this help

Matteo
  • 37,680
  • 11
  • 100
  • 115
  • I'm not a Drupal expert, possibly can be also `{% set dateLength = content.field_date['#items'] | length %}` – Matteo Jul 06 '16 at 05:01
  • 1
    Ahhh, I was definitely over complicating things. Somehow I missed the length filter when sifting through the Twig docs. Works perfectly... Thanks for your input! – m918273 Jul 06 '16 at 05:18