Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig: Append to array inside array/object

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?

like image 639
Nick Avatar asked Jun 16 '26 23:06

Nick


2 Answers

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.

like image 108
Alain Tiemblo Avatar answered Jun 19 '26 11:06

Alain Tiemblo


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.

like image 23
Nick Avatar answered Jun 19 '26 12:06

Nick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!