Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set multi-dimensional array in Twig?

Tags:

I'm working on Twig for templating in my Symfony2 project. I need to define a 2 dimensional array. I tried like

{% set fields = { {'name': 'description', 'value':  '1'}, { 'name': 'abc', 'value': '2'}, { 'name':'tags', 'value': '3'} } %}

But I'm getting

A hash key must be a quoted string, a number, a name, or an expression enclosed in parentheses (unexpected token "punctuation" of value "{" in ABundle:XYZ:edit_a_page.html.twig at line 51  

Not sure what is wrong with the above code.

What is the right syntax to set a 2 dimensional array in twig?

like image 435
Ramesh Avatar asked Mar 13 '14 08:03

Ramesh


2 Answers

In Twig, arrays are marked with [], and hashes with {}. A hash is a key-value pair with explicit keys (strings or integers), an array is simply a set of values without any explicitly defined keys (they will be indexed numerically).

In order to use a hash, you MUST provide a key for each element.

So, what you want is probably {% set fields = [ {'name': 'description', 'value': '1'}, { 'name': 'abc', 'value': '2'}, { 'name':'tags', 'value': '3'} ] %}

like image 185
Buga Dániel Avatar answered Sep 17 '22 10:09

Buga Dániel


You can do it like this {% set foo = {"adjuster_list": {"id": "1", "name": "Joe Smith"}} %}

like image 45
user1529918 Avatar answered Sep 17 '22 10:09

user1529918