Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop by integer value with Nunjucks Templating

Tags:

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.

like image 600
Jamie Bradley Avatar asked Sep 21 '15 17:09

Jamie Bradley


People also ask

Why does nunjucks not support synchronous for loops?

The reason those tags are separate is performance; most people use templates synchronously and it's much faster for forto compile to a straight JavaScript forloop. At compile-time, Nunjucks is not aware how templates are loaded so it's unable to determine if an includeblock is asynchronous or not.

How to write a for loop based on numberofrooms value?

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.

What is nunjucks templating?

Templating This is an overview of the templating features available in Nunjucks. Nunjucks is essentially a port of jinja2, so you can read their docsif you find anything lacking here. Read about the differences here. User-Defined Templates Warning

What is the use of nunjucks in Python?

Nunjucks allows you to operate on values (though it should be used sparingly, as most of your logic should be in code). The following operators are available: Addition: + Subtraction: - Division: / Division and integer truncation: // Division remainder: % Multiplication: * Power: **


1 Answers

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 %} 
like image 134
Jerome WAGNER Avatar answered Sep 28 '22 08:09

Jerome WAGNER