m918273
m918273

Reputation: 110

Loop through fields in Drupal 8

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.

Upvotes: 2

Views: 2794

Answers (1)

Matteo
Matteo

Reputation: 39410

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

Upvotes: 2

Related Questions