Twig - Why does it not allow us to set object / ar

2019-06-27 18:59发布

问题:

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.

回答1:

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

{% set entry = entry|merge({'depth': 1}) %}