Score:0

How can I correctly use an if-condition along with a for-loop in Twig 3.x?

cn flag

The Upgrade Status module tells me this code is no longer valid for Drupal 10 but I'm not sure how that needs to be changed.

{% for paragraph in card_page.entity.field_paragraphs if not break %}
  {% set _paragraph = paragraph.entity %}
  {% set _paragraph_type = paragraph.entity.type.entity %}
  {% if _paragraph_type.id == 'landing_hero' %}
    {% set break = true %}
    {% set image_id = _paragraph.field_image.0.entity.id %}
    {% set image_file = file_url(_paragraph.field_image.0.entity.uri.value) %}
  {% endif %}
{% endfor %}
Score:0
cn flag

Drupal 10 updated Twig from 2.x to 3.x. The {% for ... if ... %} statement is removed from Twig 3.x.

In Twig 3.x put the if statement outside the loop or in the loop body:

{% set break = false %}
{% for paragraph in card_page.entity.field_paragraphs %}
  {% if not break %}
    {% set _paragraph = paragraph.entity %}
    {% set _paragraph_type = paragraph.entity.type.entity %}
    {% if _paragraph_type.id == 'landing_hero' %}
      {% set break = true %}
      {% set image_id = _paragraph.field_image.0.entity.id %}
      {% set image_file = file_url(_paragraph.field_image.0.entity.uri.value) %}
    {% endif %}
  {% endif %}
{% endfor %}

See the change record https://www.drupal.org/node/3256890

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.