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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With