[1.1.x] Use "is sequence" Twig test to prevent fatal errors when looping on slots

Created on 30 October 2024, about 2 months ago

Problem/Motivation

If you use Grid Row component in a view and you have only one result, you will get this fatal error:

Exception: Object of type Drupal\node\Entity\Node cannot be printed. in Drupal\Core\Template\TwigExtension->escapeFilter()

Because content is a single renderable, so we are looping on the renderable properties:

  {% for item in content %}
    {% set col_sizes = [fr_col, fr_col_sm, fr_col_md, fr_col_lg, fr_col_xl] %}
    <div{{ create_attribute({class: col_sizes}) }}>
      {{ item }}
    </div>
  {% endfor %}

Proposed resolution

Since Twig 3.11, there are 2 new tests: is sequence and is mapping, so we can use them to check if there is a single renderable and wrap it into a sequence before looping:

  {% set content = content is sequence ? content : [content] %}

However, we will need to wait the move to 1.1.x branch because the 1.0.x branch is still supporting Drupal 9:

This change need to be done everywhere there is a loop on a slot:

components/accordion_group/accordion_group.twig:    {% for accordion in accordions %}
components/badge_group/badge_group.twig:    {% for badge in badges %}
components/button_group/button_group.twig:    {% for button in buttons %}
components/download_link_group/download_link_group.twig:      {% for download in downloads %}
components/grid_row/grid_row.twig:  {% for item in content %}
components/link_group/link_group.twig:    {% for link in links %}
components/tag_group/tag_group.twig:    {% for tag in tags %}

What else?

📌 Task
Status

Active

Version

1.0

Component

Code

Created by

🇫🇷France pdureau Paris

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024