Reputation: 8162
I wonder why this do not work
{% set what = 'hate' %}
{% set byValue = 'like' %}
{{ 'I hate twig'|replace( { what : byValue } ) }}
It should display I like twig
isn't it?
Upvotes: 2
Views: 1473
Reputation: 36954
The syntax to create associative arrays using Twig is:
{key1: value1, key2: value2, 'key3': value3, (key4): value4}...
Take care here:
key1 and key2 are HASH KEYS
'key3' is a string
(key4) is an EXPRESSION (it evaluates your key4 variable)
value1 ... value4 are variables
HASH KEYS are basically literally considered as strings.
So, your array:
{ what : byValue }
Will create an array with a what
key, instead of the content of your what
variable. If you want to use an expression instead of a hash key, you just need to wrap your hash key (or even a number) with parenthesis.
{ (what) : byValue }
Upvotes: 4
Reputation: 145398
Just wrap the key with parentheses and Twig will treat it as a variable:
{{ 'I hate twig'|replace({ (what): byValue }) }}
Upvotes: 6
Reputation: 2379
Should
{{ 'I hate twig'|replace( { what : byValue } )) }}
be
{{ 'I hate twig'|replace( { what : byValue } ) }}
Upvotes: 0