问题
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.
回答1:
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 %}
来源:https://stackoverflow.com/questions/32701303/loop-by-integer-value-with-nunjucks-templating