Loop by integer value with Nunjucks Templating

2019-04-04 08:41发布

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条回答
Anthone
2楼-- · 2019-04-04 09:01

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 %}
查看更多
登录 后发表回答