Search code examples
for-looptemplatingnunjucks

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.


Solution

  • 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