Loop by integer value with Nunjucks Templating
Asked Answered
P

1

28

I'm quite new to nunjucks and from what I have read this is not possible, but I was wondering if anyone had come up with a way of doing this.

I am basically looking to perform a for loop in a nunjucks template based on a value rather than an object's size.

Say you pass the following data to a template. Assume the number of rooms value is the value of a selected option from a <select> element :

data : {
 numberOfRooms : 4
}

In traditional JS I could write a for loop and limit the loop based on the numberOfRooms value:

for (var i = 0; i < data.numberOfRooms; i ++) {
  // do something...
}

My end goal is write a loop in a Nunjucks template that will duplicate a block of markup X number of times where X is the numberOfRooms value.

So, if this is possible, how would one achieve this with Nunjucks? If this completely defeats the purpose of Nunjucks then please say and any alternative suggestions would be greatly appreciated.

Prue answered 21/9, 2015 at 17:34 Comment(0)
A
47

you should be able to use the range construct - https://mozilla.github.io/nunjucks/templating.html#range-start-stop-step

{% for i in range(0, data.numberOfRooms) -%}
  {{ i }},
{%- endfor %}
Akim answered 21/9, 2015 at 18:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.