我正在尝试从Nunjucks的 {% for %}
循环中获取数组中项的索引,但遇到了一些问题。
我要操作的数组非常简单,长这样
pages[1,2,3]
这是 Nunjucks 循环示例:
{% for i,p in data.tickets.pages %}
{{ i }} : {{ p }}
{% endfor %}
问题是:
{{ p }}
输出 1,2,3
,但 {{ i }}
没有输出任何内容。
我正在尝试从Nunjucks的 {% for %}
循环中获取数组中项的索引,但遇到了一些问题。
我要操作的数组非常简单,长这样
pages[1,2,3]
这是 Nunjucks 循环示例:
{% for i,p in data.tickets.pages %}
{{ i }} : {{ p }}
{% endfor %}
{{ p }}
输出 1,2,3
,但 {{ i }}
没有输出任何内容。
loop.index
(loop.index从1
开始)0
开始),请使用loop.index0
data.tickets.pages = [1, 2, 3];
loop.index
){% for page in data.tickets.pages %}
{{loop.index}}: {{ page }}
{% endfor %}
输出
1:1
2:2
3:3
loop.index0
){% for page in data.tickets.pages %}
{{loop.index0}}: {{ page }}
{% endfor %}
输出
0:1
1:2
2:3
loop.index
: 循环的当前迭代次数(从1开始计数)loop.index0
: 循环的当前迭代次数(从0开始计数)loop.revindex
: 到循环结束还有几次迭代(从1开始计数)loop.revindex0
: 到循环结束还有几次迭代(从0开始计数)loop.first
: 表示是否是第一次迭代的布尔值loop.last
: 表示是否是最后一次迭代的布尔值loop.length
: 总项目数nunjucks
等待单个迭代器用于 array
。当您使用多个迭代器并传递 array
时,nunjucks
会将每个 array
元素按照迭代器集合进行拆分。{% set pages = [[10, 11], [12, 13]] %}
{% for a, b in pages %}
{{a}},{{b}}
{% endfor %}
---
10:11
12:13
range
,将数组转换为对象(元素顺序可能会丢失),或者使用loop.index0
/ loop.index
。var nunjucks = require('nunjucks');
var env = nunjucks.configure();
// range
var res = nunjucks.renderString(`
{% for i in range(0, items.length) %}
{% set item = items[i] %}
{{i}}: {{item}}
{% endfor %}`,
{items: [10, 12]}
);
console.log(res);
// array to object
res = nunjucks.renderString(`
{% for i, item in items %}
{{i}}: {{item}}
{% endfor %}`,
{items: Object.assign({}, [10, 12])}
);
console.log(res);
// loop.index0
res = nunjucks.renderString(`
{% for item in items %}
{{loop.index0}}: {{item}}
{% endfor %}`,
{items: [10, 12]}
);
console.log(res);
对于通过Google或其他方式来到这里的任何人。我能够直接在我的模板中使用上面描述的范围循环方法,甚至可以嵌套循环。
以下是我在nunjucks模板中的部分代码:
<ul class="index">
{% for x in range(0, dbReport.sections.length) %}
{% set section = dbReport.sections[x] %}
<li>
<strong>{{ x + 1 }}</strong> {{ section.sectionTitle }}
<ul>
<li>
<strong>{{ x + 1 }}.1</strong> Section components:
<ul>
{% for y in range(0, section.subSections.length) %}
{% set subSection = section.subSections[y] %}
<li>
<strong>{{ x + 1 }}.1.{{ y + 1 }}</strong> {{subSection.subSectionTitle}}
</li>
{% endfor %}
</ul>
</li>
</ul>
</li>
{% endfor %}
</ul>
{%- for pageIndex, page in collections.pages.entries() -%}
<div class="page" id="page-{{ pageIndex + 1 }}">
{{ page.templateContent | safe }}
</div>
{%- endfor -%}