javascript 使用 Nunjucks 模板按整数值循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32701303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 15:38:05  来源:igfitidea点击:

Loop by integer value with Nunjucks Templating

javascriptnode.jstemplatingnunjucks

提问by Jamie Bradley

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.

我基本上希望在 nunjucks 模板中根据值而不是对象的大小执行 for 循环。

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 :

假设您将以下数据传递给模板。假设房间数值是从<select>元素中选择的选项的值:

data : {
 numberOfRooms : 4
}

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

在传统的 JS 中,我可以编写一个 for 循环并根据numberOfRooms值限制循环:

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.

我的最终目标是在 Nunjucks 模板中编写一个循环,该循环将复制标记块 X 次,其中 X 是 numberOfRooms 值。

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.

那么,如果这是可能的,人们将如何通过 Nunjucks 实现这一目标?如果这完全违背了 Nunjucks 的目的,那么请说,任何其他建议将不胜感激。

回答by Jerome WAGNER

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

您应该能够使用该range构造 - https://mozilla.github.io/nunjucks/templating.html#range-start-stop-step

{% for i in range(0, data.numberOfRooms) -%}
  {{ i }},
{%- endfor %}