For loop 存储细枝循环,以便多次重复使用

For loop 存储细枝循环,以便多次重复使用,for-loop,twig,template-engine,For Loop,Twig,Template Engine,我循环了两个数组,但它们是嵌套的。 减少到最小值后,看起来如下所示: {% for item in items %} <label>{{ item.name }}</label> <select> {% for attribute in attributes %} <option>{{ attribute.name }}</option> {% endfor %} </se

我循环了两个数组,但它们是嵌套的。 减少到最小值后,看起来如下所示:

{% for item in items %}
    <label>{{ item.name }}</label>

    <select>
    {% for attribute in attributes %}
        <option>{{ attribute.name }}</option>
    {% endfor %}
    </select>

{% endfor %}
{items%]中的项的%
{{item.name}
{attributes%%中的属性为%s}
{{attribute.name}
{%endfor%}
{%endfor%}
问题在于阵列的大小。大约有1100个
项目
和400个
属性
。正如人们可以猜测的那样,这是缓慢的。非常慢


是否可以“存储”内部循环,然后重用生成的/渲染的块?

将内部循环移到外部循环之外,然后将生成的值存储在细枝变量中。然后运行外部循环,在
标记之间提供变量。这样,只生成一次内部循环

{% set options = '' %}
{% for attribute in attributes %}
    {% set options = options ~ '<option>' ~ attribute.name ~ '</option>' %}
{% endfor %}

{% for item in items %}
    <label>{{ item.name }}</label>
    <select>
        {{ options }}
    </select>
{% endfor %}
{%set options='''%}
{attributes%%中的属性为%s}
{%set options=options~''~attribute.name~''%}
{%endfor%}
{items%%中的项的%s}
{{item.name}
{{options}}
{%endfor%}

哦,对不起。我为这个问题设置了电子邮件信息,但没有。今天下班后我要试试。我一直在找这样的东西,但我觉得它很有前途。今天晚些时候,我会让你知道这对我有用。非常感谢,这就是我一直在寻找的答案。有两件事我必须改变:
{{options}}
一个太多的花括号,因为var是html代码,我必须设置“var”过滤器:
{options}}
。doh typo,phpsform自动完成花括号,同时我把它们放进去,修复了。