如何在Twig中设置多维数组?

时间:2021-03-28 21:27:58

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

我在Symfony2项目中正在研究Twig的模板。我需要定义一个二维数组。我试过了

{% 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?

在树枝中设置二维数组的正确语法是什么?

2 个解决方案

#1


27  

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).

在Twig中,数组用[]标记,哈希用{}标记。散列是具有显式键(字符串或整数)的键值对,数组只是一组没有任何明确定义键的值(它们将以数字方式索引)。

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

那么,你想要的可能是{%set fields = [{'name':'description','value':'1'},{'name':'abc','value':'2'},{ 'name':'tags','value':'3'}]%}

#2


1  

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

你可以这样做{%set foo = {“adjuster_list”:{“id”:“1”,“name”:“Joe Smith”}}%}

#1


27  

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).

在Twig中,数组用[]标记,哈希用{}标记。散列是具有显式键(字符串或整数)的键值对,数组只是一组没有任何明确定义键的值(它们将以数字方式索引)。

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

那么,你想要的可能是{%set fields = [{'name':'description','value':'1'},{'name':'abc','value':'2'},{ 'name':'tags','value':'3'}]%}

#2


1  

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

你可以这样做{%set foo = {“adjuster_list”:{“id”:“1”,“name”:“Joe Smith”}}%}