Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By lauriii on
Change record status:
Published (View all published change records)
Project:
Introduced in branch:
10.0.x
Introduced in version:
10.0.0
Issue links:
Description:
The new Twig |add_suggestion
filter allows adding a theme suggestion to a render array rendered with #theme
. For example, if content.body
has a render array with '#theme' => 'field'
, using the |add_suggestion
filter with the variable {{ content.body|add_suggestion('details') }}
would allow loading a template field--details.html.twig
.
The theme suggestion added with |add_suggestion
will have the highest priority, and will take precedence over any pre-existing theme suggestions.
Unordered list field example
{{ content.field_items|add_suggestion('unordered-list') }}
{# field--unordered-list.html.twig #}
{% extends 'field.html.twig' %}
{% block content %}
<ul{{ attributes }}>
{{ parent() }}
</ul>
{% endblock content %}
{% block item %}
<li{{ item.attributes }}>{{ parent() }}</li>
{% endblock item %}
Link list field example
{{ content.field_links|add_suggestion('link-list') }}
{# field--link-list.html.twig #}
{% extends 'field--unordered-list.html.twig' %}
{# Add link list classes to list element and items. #}
{% set attributes = attributes.addClass('link-list--items') %}
{% set items = items|map(item => item|merge({
attributes: item.attributes.addClass('link-list--item'),
}))
%}
{# Attach helper JS to apply external icon treatment. #}
{% block content %}
{{ attach_library('my_theme/link_list_icons') }}
{{ parent() }}
{% endblock content %}
Element tag (div, p, span, h2, h3, etc) field example
{{ label|add_suggestion('h4') }}
{# field--h4.html.twig #}
{% extends 'field.html.twig' %}
{% block content %}
<h4{{ attributes }}>{{ parent() }}</h4>
{% endblock content %}
Impacts:
Themers