php 从 Twig 设置数组元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9432534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting element of array from Twig
提问by falinsky
How can I set member of an already existing array from Twig?
如何从 Twig 设置现有数组的成员?
I tried doing it next way:
我尝试这样做:
{% set arr['element'] = 'value' %}
but I got the following error:
但我收到以下错误:
Unexpected token "punctuation" of value "[" ("end of statement block" expected) in ...
值“[”(预期“语句块结束”)的意外标记“标点符号”在......
回答by Paul
There is no nice way to do this in Twig. It is, however, possible by using the merge filter:
在 Twig 中没有好的方法可以做到这一点。但是,可以通过使用合并过滤器:
{% set arr = arr|merge({'element': 'value'}) %}
回答by LivaX
I ran into this problem but was trying to create integer indexes instead of associative index like 'element'.
我遇到了这个问题,但试图创建整数索引而不是像“元素”这样的关联索引。
You need to protect your index key with ()
using the merge filter as well:
您还需要()
使用合并过滤器来保护您的索引键:
{% set arr = arr|merge({ (loop.index0): 'value'}) %}
You can now add custom index key like ('element'~loop.index0)
您现在可以添加自定义索引键,如 ('element'~loop.index0)
回答by pleerock
If initialization only need:
如果初始化只需要:
{% set items = { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'unknown' } %}
回答by zizoujab
I have tried @LivaX 's answer but it does not work , merging an array where keys are numeric wont work ( https://github.com/twigphp/Twig/issues/789).
我已经尝试过@LivaX 的答案,但它不起作用,合并一个键为数字的数组不起作用(https://github.com/twigphp/Twig/issues/789)。
That will work only when keys are strings
只有当键是字符串时才有效
What I did is recreate another table ( temp
) from the initial table (t
) and make the keys a string , for example :
我所做的是temp
从初始表 ( t
)重新创建另一个表 ( )并将键设为字符串,例如:
{% for key , value in t%}
{% set temp= temp|merge({(key~'_'):value}) %}
{% endfor %}
t
keys : 0 , 1 , 2 ..
t
键: 0 , 1 , 2 ..
temp
keys : 0_, 1_ , 2_ ....
temp
键: 0_, 1_ , 2_ ....
回答by n8tron
{% set links = {} %}
{# Use our array to wrap up our links. #}
{% for item in items %}
{% set links = links|merge({ (loop.index0) : {'url': item.content['#url'].getUri(), 'text': item.content['#title']} }) %}
{% endfor %}
{%
set linkList = {
'title': label,
'links': links
}
%}
{% include '<to twig file>/link-list.twig'%}
Thanks for this thread -- I was also able to create an array with (loop.index0) and send to twig.
感谢这个线程——我还能够使用 (loop.index0) 创建一个数组并发送到 twig。
回答by savedario
I've found this issue very annoying, and my solution is perhaps orthodox and not inline with the Twig philosophy, but I developed the following:
我发现这个问题很烦人,我的解决方案可能是正统的,不符合 Twig 哲学,但我开发了以下内容:
$function = new Twig_Function('set_element', function ($data, $key, $value) {
// Assign value to $data[$key]
if (!is_array($data)) {
return $data;
}
$data[$key] = $value;
return $data;
});
$twig->addFunction($function);
that can be used as follows:
可以按如下方式使用:
{% set arr = set_element(arr, 'element', 'value') %}
{% set arr = set_element(arr, 'element', 'value') %}
回答by user1321109
Just use this like {% set arr={'key':'value'} %}
(with no blank space after the :
), it works well.
就像这样使用{% set arr={'key':'value'} %}
(在 之后没有空格:
),它运行良好。
But when I use it inside a for loop, to make it an array, it does not work outside of the for scope.
但是当我在 for 循环中使用它以使其成为数组时,它在 for 范围之外不起作用。
{% for group in user.groups %}
{% set foo={'loop.index0':'group.id'} %}
{% set title={'loop.index0':'group.title'} %}
{{ title }} //it work
{% else %}
{% set foo={'0':'-1'} %}
{% set title={'0':'未分组'} %}
{% endfor %}
{{ title }} //it does not work, saying title is not defined
回答by shobekhan
I had a multi dimension array. The only solution I could find out is create a new temporary array and update/addthe information, which was further passed on to another twig function.
我有一个多维数组。我能找到的唯一解决方案是创建一个新的临时数组并更新/添加信息,该信息被进一步传递给另一个树枝函数。
回答by Teocci
I had this problem sometime ago. Imagine you have an array like this one:
我前一段时间遇到过这个问题。想象一下你有一个这样的数组:
data = {
'user': 'admin',
'password': 'admin1234',
'role': 'admin',
'group': 'root',
'profile': 'admin',
'control': 'all',
'level': 1,
'session': '#DFSFASADASD02',
'pre_oa': 'PRE-OA',
'hepa_oa': 'HEPA-OA',
'pre_ra': 'HEPA-RA',
'hepa_ra': 'HEPA-RA',
'deodor_ra': 'DEODOR-RA'
}
So, you want to show this data in two rows, but remove the password from that list. To this end, split in 2 arrays will be easy with the slice
filter. However, we have to remove the password. For that reason, I'm using this snippet. The idea is to put all the elements lesser than the data
elements size divided by 2. To calculate this we use the filter length
. Now to get the index of the current element we user loop.index
. And finally we *push an associative element in the left or right array. An associative array has two components key
and value
. To reference an array key in twit we operator ()
and we use the merge
filter to push into the array as shown here {% set left_list = left_list|merge({ (key): value }) %}
因此,您希望在两行中显示此数据,但从该列表中删除密码。为此,使用slice
过滤器将很容易分成 2 个数组。但是,我们必须删除密码。出于这个原因,我正在使用这个片段。这个想法是将所有小于data
元素大小除以 2的元素放入。为了计算这个,我们使用 filter length
。现在要获取我们 user 的当前元素的索引loop.index
。最后我们 *push 左数组或右数组中的关联元素。关联数组有两个组件key
和value
。要在 twit 中引用数组键,我们操作()
并使用merge
过滤器推入数组,如下所示{% set left_list = left_list|merge({ (key): value }) %}
This is the complete solution.
这是完整的解决方案。
{% set left_list = {} %}
{% set right_list = {} %}
{% set limit = data|length // 2 %}
{% for key, value in data|cast_to_array %}
{% if key != 'password' %}
{% if loop.index <= limit %}
{% set left_list = left_list|merge({ (key): value }) %}
{% else %}
{% set right_list = right_list|merge({ (key): value }) %}
{% endif %}
{% endif %}
{% endfor %}
{% for key, value in left_list %}
<p>
<label for="{{key}}">{{key}}</label>
<input type="text" name="{{key}}" id="{{key}}" value="{{value}}"
class="text ui-widget-content ui-corner-all">
</p>
{% endfor %}
回答by GarryOne
You can also use the following syntax:
您还可以使用以下语法:
{% set myArray = myArray + myArray2 %}