我设置一个“类别”并将其传递给我包含的模板:
{% set categoryA = {
category: "categoryA",
}
%}
{% include "something.twig" with categoryA %}
{% set categoryB = {
category: "categoryB",
}
%}
{% include "something.twig" with categoryB %}
这工作正常,但我重复了很多我想避免的代码(在我的实际代码中有超过2个类别)。
我试图将类别放在一个数组中,并为每个类别包含something.twig,为每个实例传递一个不同的类别:
{% set categories = ['categoryA', 'categoryB', 'categoryC', 'categoryD', 'categoryE'] %}
{% for i in categories %}
<h3>{{ i }}</h3>
{% set categoryOption = {
category: {{ i }},
}
%}
{% include "something.twig" with categoryOption %}
{% endfor %}
打印h3中的标题OK但是categoryOption类别作为[object Object]传递,而不是我需要的字符串名称
答案 0 :(得分:0)
例如,您在“something.twig”中使用类别:
...
{{ category|default }}
...
所以你可以使用“include”,如:
{% include "something.twig" with { category: 'Name of Category' } %}
完整代码:
{% set categories = ['categoryA', 'categoryB', 'categoryC', 'categoryD', 'categoryE'] %}
{% for i in categories %}
<h3>{{ i }}</h3>
{% include "something.twig" with { category: i } %}
{% endfor %}