假设我有一个项目集合
$collection = array(
'item1' => array(
'post' => $post,
'category' => $category,
// ...
),
'item2' => array(...)
);
我有一个模板:
{% for item in collection %}
Now I can use item data
- {{ item.post.title }}
- {{ item.category.id }}
- {{ item.var1 }}
- {{ item.var2 }}
- and another 20 vars
I want to extract those vars into more global FOR context, and use them as:
{{ post.title }}
{{ category.id }}
{{ var1 }}
... etc
{% endfor %}
这可能吗?
我想将循环定义为模板 block ,然后使用 Twig_Template::renderBlock() 对其进行迭代。但是文档说 renderBlock 仅供“内部”使用 :) 所以不确定。
编辑:
我的另一个想法:
{% for item in collection %}
{% do extract(item) %}
// extract() would work similar to extract function from php
{% endfor %}
但是,上下文似乎是按值传递给 twig 函数的,所以这是行不通的。
最后我可以写一个 TokenParser 并做:
{% for item in collection %}
{% extract item %}
// would probably get direct access to the context, but haven't tried it
{% endfor %}
但这是相当多的工作..我只是希望 twig 已经可以原生地做到这一点:)
最佳答案
您可以使用宏: http://twig.sensiolabs.org/doc/tags/macro.html
{% import _self as macro %}
{% macro render(item) %}
{{ item.post.title }}
{{ item.category.id }}
{{ item.var1 }}
{{ item.var2 }}
...
{% endmacro %}
{% for item in collection %}
{{ macro.render(item) }}
{% endfor %}
关于Twig 提取 FOR 循环变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36034519/