I'm having some trouble getting indexes of a items in an array from a Nunjucks {% for %}
loop.
The array I am targeting is simple and looks like this
pages[1,2,3]
And this is the Nunjucks loop
{% for i,p in data.tickets.pages %}
{{ i }} : {{ p }}
{% endfor %}
The problem is
{{ p }}
outputs 1,2,3
but {{ i }}
doesn't output anything.
If anyone can tell me how to fix this, I'd much appreciate it.
To get the index in a for loop use loop.index
(loop.index starts with a 1
)
To get the standard behavior (start with a 0
) use loop.index0
data.tickets.pages = [1, 2, 3];
loop.index
){% for page in data.tickets.pages %}
{{loop.index}}: {{ page }}
{% endfor %}
Output
1:1
2:2
3:3
loop.index0
){% for page in data.tickets.pages %}
{{loop.index0}}: {{ page }}
{% endfor %}
Output
0:1
1:2
2:3
loop.index
: the current iteration of the loop (1 indexed)loop.index0
: the current iteration of the loop (0 indexed)loop.revindex
: number of iterations until the end (1 indexed)loop.revindex0
: number of iterations until the end (0 based)loop.first
: boolean indicating the first iterationloop.last
: boolean indicating the last iterationloop.length
: total number of itemsTipically nunjucks
wait single iterator for array
.
When you use multi-iterator and pass array
, nunjucks
split each array
element by iterator set.
{% set pages = [[10, 11], [12, 13]] %}
{% for a, b in pages %}
{{a}},{{b}}
{% endfor %}
---
10:11
12:13
You can use range
, convert array to object (element order can be lost) or use 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With