Iteration
Pug supports two primary methods of iteration: each
and while
.
each
Pug’s first-class iteration syntax makes it easier to iterate over arrays and objects in a template:
ul
each val in [1, 2, 3, 4, 5]
li= val
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
You can also get the index as you iterate:
ul
each val, index in ['zero', 'one', 'two']
li= index + ': ' + val
<ul>
<li>0: zero</li>
<li>1: one</li>
<li>2: two</li>
</ul>
Pug also lets you iterate over the keys in an object:
ul
each val, index in {1:'one',2:'two',3:'three'}
li= index + ': ' + val
<ul>
<li>1: one</li>
<li>2: two</li>
<li>3: three</li>
</ul>
The object or array to iterate over is just plain JavaScript. So, it can be a variable, or the result of a function call, or almost anything else.
- var values = [];
ul
each val in values.length ? values : ['There are no values']
li= val
<ul>
<li>There are no values</li>
</ul>
One can also add an else
block that will be executed if the array or object does not contain values to iterate over. The following is equivalent to the example above:
- var values = [];
ul
each val in values
li= val
else
li There are no values
<ul>
<li>There are no values</li>
</ul>
You can also use for
as an alias of each
.
while
You can also use while
to create a loop:
- var n = 0;
ul
while n < 4
li= n++
<ul>
<li>0</li>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>