使用Nunjucks Templating循环整数值 [英] Loop by integer value with Nunjucks Templating

查看:388
本文介绍了使用Nunjucks Templating循环整数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对nunjucks很新,从我所看到的这是不可能的,但我想知道是否有人想出办法。



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



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

 数据:{
numberOfRooms:4
}

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

  for(var i = 0; i< data.numberOfRooms; i ++){
//做某事......
}

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



所以,如果可以的话,Nunjucks会如何实现这个目标?如果这完全违背了Nunjucks的目的那么请说,并且非常感谢任何其他建议。

解决方案

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

  { i在范围内的百分比(0,data.numberOfRooms) - %} 
{{i}},
{% - endfor%}


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.

解决方案

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 %}

这篇关于使用Nunjucks Templating循环整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆