25

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?

1
  • 2
    Try thinking about JSON next time, TWIG nearly has the same array syntax Commented Mar 13, 2014 at 9:03

2 Answers 2

43

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'} ] %}

Sign up to request clarification or add additional context in comments.

3 Comments

So how would you change the main key? At the moment it's still 0,1,2,3 etc.
If you want to set your own unique keys, use the hash syntax (outer curly braces rather than square brackets) and put the key followed by a colon before each one, as in user1529918's answer. Also useful: Twig's dump function, to verify what it's seeing.
Hi, this may be a dumb question, but what class of object is this hash? It's just an associative array? Would json.decode('{{...},{....}}') make an object of the same class?
3

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

2 Comments

Or like this: {% set foo = {"adjuster_list": [{"id": 1, "name": "Joe Smith"}]} %}
That is helpful. Or it is in JSON style.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.