Attempting to merge in an array of items into Twig classes
-
02-03-2021 - |
Domanda
I have a Twig template where I'd like to merge in an array of items as classes. So far I have this code:
{% set classes = [
'media',
'media--type-' ~ media.bundle()|clean_class,
not media.isPublished() ? 'media--unpublished',
view_mode ? 'media--view-mode-' ~ view_mode|clean_class,
] %}
{% for item in content.field_category | children(true) %}
{% set classes = classes|merge(item) %}
{% endfor %}
<section{{ attributes.addClass(classes) }}>
etc...
Note that {% for item in content.field_category | children(true) %}
is using Twig Tweak.
In this case for example, item
represents term values for each item in plain text as:
Nature
Travel
Architecture
and then with <section{{ attributes.addClass(classes) }}>
, I'd like the set classes as well as my custom classes to all be merged together. However, I am getting an error:
Notice: Array to string conversion in Drupal\Core\Template\AttributeArray->__toString() (line 73 of core/lib/Drupal/Core/Template/AttributeArray.php).
So this tells me, I did not merge the array of items properly but I am lost after this, not sure how to fix it. My guess is, I need to do this without a for
loop somehow?
Soluzione
Twig's merge filter expects an array as an argument, not a string.
Updating your for loop should resolve:
{% for item in content.field_category | children(true) %}
{# Merge classes array with an array with one item, item #}
{% set classes = classes|merge([item]) %}
{% endfor %}