0

I want to add multiple class to my {{item}} twig template. The following code

{% set item = item|merge({'#attributes': { 'class': 'project-label'}}) %}

sets only one class ... how can I assign multiple class ? can i do something like this

{% set item = item|merge({'#attributes': { 'class': 'project-label'}}),
({'#attributes': { 'class': 'project-term{{ loop.index }}'}}`)%}

Please help.

Thanks

2
  • Did you check this question?
    – Jimmy Ko
    Commented Nov 24, 2016 at 14:13
  • yes ... the thing is I want to use the {{loop.index}} on the second class Commented Nov 24, 2016 at 14:19

1 Answer 1

1

Put the classes in an array:

{%
  set itemclasses = [
    'project-label',
    'project-term' ~ loop.index,
  ]
%}

And add the array to attributes:

{% set item = item|merge({'#attributes': { 'class': itemclasses } }) %}
5
  • the loop.index is not looping --- i does print out the classes as expected but the loop.index count is missing. Commented Nov 24, 2016 at 14:45
  • Did you place the code to set itemclasses also in the loop?
    – 4uk4
    Commented Nov 24, 2016 at 14:50
  • yes the itemclasses is within a for loop Commented Nov 24, 2016 at 14:54
  • This is what i have {% set itemclasses = [ 'project-label', 'project-term' ~ loop.index, ] %} {% for child in children %} {% set item = attribute(element, child) %} {% set item = item|merge ({'#attributes': { 'class': itemclasses }}) %} <li > {{ item }} </li> {% endfor %} Commented Nov 24, 2016 at 15:00
  • You have to start with the for loop before you set the itemclasses. Outside of the loop the loop variables are undefined.
    – 4uk4
    Commented Nov 24, 2016 at 16:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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