user2143356
user2143356

Reputation: 5607

Twig / Symfony2 - using a variable inside array merge

{% set var_name1 = "hello" %}
{% set var_name2 = "there" %}
{% array1|merge({var_name1: var_name2}) %}

I was hoping the code above would add this to array1:

hello:there

...but it adds:

var_name1:there

I've tried wrapping {{ }} around var_name1. Is it possible to add a record to an array and use a variable for the key?

Upvotes: 2

Views: 2927

Answers (2)

jam-jam
jam-jam

Reputation: 31

Note that if var_name1 is a numeric value, it won't work. You'll have to concat it with a string value :

{% set array1 = array1|merge({(var_name1~'_'): var_name2}) %}

Upvotes: 2

Vadim Ashikhman
Vadim Ashikhman

Reputation: 10136

Enclose the key name in brackets:

{% array1|merge({(var_name1): var_name2}) %}

Upvotes: 10

Related Questions