Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot get index of item in array with Nunjucks for loop

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.

like image 476
mikeym Avatar asked Aug 23 '17 17:08

mikeym


2 Answers

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];

Template code (loop.index)

{% for page in data.tickets.pages %}
  {{loop.index}}: {{ page }}
{% endfor %}

Output

1:1
2:2
3:3

Template code (loop.index0)

{% for page in data.tickets.pages %}
  {{loop.index0}}: {{ page }}
{% endfor %}

Output

0:1
1:2
2:3

See Also the nunjucks docs

  • 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 iteration
  • loop.last: boolean indicating the last iteration
  • loop.length: total number of items
like image 192
BenRoe Avatar answered Oct 28 '22 16:10

BenRoe


Tipically 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);
like image 1
Aikon Mogwai Avatar answered Oct 28 '22 15:10

Aikon Mogwai