Loop through an arbitrary number of items in Nunjucks

Loop through an arbitrary number of items using the Nunjucks range function. This is very useful when prototyping to generate dummy markup or content. This example outputs 10 <div> elements:

{% for i in range(0, 10) %}
  <div></div>
{% endfor %}

You can also include the index in the output, like so:

{% for i in range(0, 10) %}
  <div>{{ i }}</div>
{% endfor %}

I used this concept all the time when prototypying with Pug, but since I’ve been working with Eleventy more I’ve decided to switch to using Nunjucks where feasible, so I’m re-learning some old techniques. For completeness, here’s the Pug method:

for i in Array(9)
  div #{i}

Next post

Previous post