How do I manipulate a variable's property in Twig? I want to add classes to a link render element that's a property of the {{content}} variable in my template.

I can do this:

{% set link = content.my_link %}
{% set link = link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}


But I don't seem to be able to manipulate content.my_link directly. Why can't I do this:

{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ content.my_link }}
{% doesn't render, and merge doesn't operate by reference. With those two things in mind, this:

{% content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}


does nothing, except to waste CPU cycles; you're not rendering, nor saving, the result of the merge.

There are various ways to solve, this is probably the simplest:

{% set link = content.my_link|merge({ '#attributes': { 'class': [ 'my-class', 'other-class', 'third-class' ] } }) %}
{{ link }}