3

I have an object which, in JSON, would look like this:

{
  'class': ['nav-link', 'dropdown-toggle'],
  'data-toggle': ['dropdown']
}

I need to then be able to append another class to the class array inside the object.

This code doesn't seem to work; it just overwrites the class array.

{% set link_attribs = { 'class' : ['nav-link', 'dropdown-toggle'], 'data-toggle':'dropdown'} %}
{% set link_attribs = link_attribs|merge({'class': ['highlighted']}) %}

Really I want to do something like this, but it just throws a punctuation error.

{% set link_attribs.class = link_attribs.class|merge(['highlighted']) %}

Any ideas?

1

2 Answers 2

5

Using Twig, you can't set object properties directly, so "set (...).class" will never work. But instead, you can create a new variable that will inherit from both default and options values (just like in most JavaScript codes).

For example:

{%
  set options = link_attribs | merge({
      'class': link_attribs.class | merge(['highlighted']) 
  })
%}

{% for class in options.class %}
  {{ class }}
{% endfor %}

Will display:

nav-link
dropdown-toggle
highlighted

See fiddle.

2
  • That looks like a bit like an inline version of my possible answer: stackoverflow.com/a/34229624/224707. It's a shame Twig doesn't like you set object properties.
    – Nick
    Dec 12, 2015 at 15:17
  • I understand your point, and in small projects this could be very useful. But changing object values in Twig doesn't make sense: as a template engine, it should only render things, without changing the application state.
    – Alain
    Dec 12, 2015 at 15:41
3

This looks like it works:

{% set c = link_attribs.class %}
{% set c = c|merge(['highlighted']) %}
{% set link_attribs = link_attribs|merge({'class': c}) %}

Not sure if its the most elegant way though.

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.