简体   繁体   English

小枝用变量迭代

[英]Twig iterate with variables

I have an array like this: 我有一个像这样的数组:

array['a'] = {x => 1, y => 2...}
array['b'] = {x => 5, y => 7...}

I need to iterate over the array, but in each case I need to enter only in the 'a' or 'b' which I choose. 我需要遍历数组,但是在每种情况下,我只需要输入选择的'a'或'b'。

{% for i in main %}
    {% set id = i.getId %}
    {% for j in array.id %}
         //do something like j.propertyA ...
    {% endfor %}
{% endfor %}

The fail is always get the error: "The key 'id' for array with keys 'a', 'b'... does not exist" 失败总是得到错误:“具有键'a','b'...的数组的键'id'不存在”

If I force writting: 如果我强迫写作:

{% for j in array.a %}

The program works fine always with array.a but I need to works with all automatically. 该程序始终可以与array.a一起正常工作,但我需要自动处理所有工作。

Any idea? 任何想法? Thanks :) 谢谢 :)

Change {% for j in array.id %} to {% for j in array[id] %} {% for j in array.id %}更改{% for j in array.id %} {% for j in array[id] %}

This is because you're trying to access " id " (as is written) directly from array (and isn't defined). 这是因为您正尝试直接从数组(未定义)访问“ id ”(按编写方式)。 With [id] your variable is substitued with its value and so your call will not fail 使用[id]您的变量将被其值替换,因此您的调用不会失败

I think you need array|keys twig filter. 我认为您需要array | key树枝过滤器。 See more: http://twig.sensiolabs.org/doc/filters/keys.html . 查看更多: http : //twig.sensiolabs.org/doc/filters/keys.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM