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.
The reason those tags are separate is performance; most people use templates synchronously and it's much faster for forto compile to a straight JavaScript forloop. At compile-time, Nunjucks is not aware how templates are loaded so it's unable to determine if an includeblock is asynchronous or not.
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.
Templating This is an overview of the templating features available in Nunjucks. Nunjucks is essentially a port of jinja2, so you can read their docsif you find anything lacking here. Read about the differences here. User-Defined Templates Warning
Nunjucks allows you to operate on values (though it should be used sparingly, as most of your logic should be in code). The following operators are available: Addition: + Subtraction: - Division: / Division and integer truncation: // Division remainder: % Multiplication: * Power: **
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 %}
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