0

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?

1

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 %}
3
  • Maybe you could also just do {% set classes = classes|merge(content.field_category|children(true)) %} – sonfd Feb 20 at 18:18
  • Thank you this worked, I actually needed to do: {% for item in content.field_category | children(true) %} {% set classes = classes|merge([item["#plain_text"]]) %} {% endfor %} ... as that was the actual item in Xdebug. Thank you! – Danny Englander Feb 20 at 18:24
  • As you are using Twig Tweak you could use with filter like this {%set classes = classes|with(item) %} – ya.teck Mar 13 at 17:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.