Loop by integer value with Nunjucks Templating

拜拜、爱过 提交于 2019-12-09 14:11:07

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!