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?

Nick
  • 2,803
  • 1
  • 39
  • 59
  • Possible duplicate of [Setting element of array from Twig](https://stackoverflow.com/questions/9432534/setting-element-of-array-from-twig) – DevLime May 31 '18 at 15:30

2 Answers2

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.

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
  • That looks like a bit like an inline version of my possible answer: http://stackoverflow.com/a/34229624/224707. It's a shame Twig doesn't like you set object properties. – Nick Dec 12 '15 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 Tiemblo Dec 12 '15 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.

Nick
  • 2,803
  • 1
  • 39
  • 59