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 = [col_xs, col_sm, col_md, col_lg, col_xl, col_xxl, spacing_margin_bottom] %}
    <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 may need to wait the move to 5.1.x branch because the 5.0.x branch is still supporting Drupal 10.2:

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

carousel/carousel.twig:    {% for slide in slides %}
grid_row/grid_row.twig:  {% for item in content %}
nav/nav.twig:    {% for pane in tab_content %}
table/table.twig:  {% for stripe in stripes %}
table/table.twig:  {% for colgroup in colgroups %}
table/table.twig:        {% for col in colgroup.cols %}

What else?

📌 Task
Status

Active

Version

5.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