Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - Why does it not allow us to set object / array values?

I'm extremely confused by the decision of Twig to not allow setting values of arrays and object properties via set.

For example, the following code will error out:

{% set entry.depth = 1 %}

Will result in the error:

Unexpected token "punctuation" of value "." ("end of statement block" expected)

Also the following way will also error (which I know twig doesn't prefer to use):

{% set entry['depth'] = 1 %}

So this effectively means we're unable to change properties of objects and arrays. I quite frankly find this bizarre.

Can someone please explain the decision behind this? Maybe if I get a technical reason why it's not possible it might make it less baffling.

Edit: Thanks for the solution, I was more after the reasoning behind the fact you have to use merge rather than just simply being able to override variables.

like image 977
Matt Cavanagh Avatar asked Aug 02 '16 08:08

Matt Cavanagh


Video Answer


1 Answers

Twig's a bit weird in this regard. You'll need to use the merge filter for this.

{% set entry = entry|merge({'depth': 1}) %}
like image 134
Bopp Avatar answered Sep 25 '22 13:09

Bopp