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:

  1. ul
  2. each val in [1, 2, 3, 4, 5]
  3. li= val
  1. <ul>
  2. <li>1</li>
  3. <li>2</li>
  4. <li>3</li>
  5. <li>4</li>
  6. <li>5</li>
  7. </ul>

You can also get the index as you iterate:

  1. ul
  2. each val, index in ['zero', 'one', 'two']
  3. li= index + ': ' + val
  1. <ul>
  2. <li>0: zero</li>
  3. <li>1: one</li>
  4. <li>2: two</li>
  5. </ul>

Pug also lets you iterate over the keys in an object:

  1. ul
  2. each val, index in {1:'one',2:'two',3:'three'}
  3. li= index + ': ' + val
  1. <ul>
  2. <li>1: one</li>
  3. <li>2: two</li>
  4. <li>3: three</li>
  5. </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.

  1. - var values = [];
  2. ul
  3. each val in values.length ? values : ['There are no values']
  4. li= val
  1. <ul>
  2. <li>There are no values</li>
  3. </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:

  1. - var values = [];
  2. ul
  3. each val in values
  4. li= val
  5. else
  6. li There are no values
  1. <ul>
  2. <li>There are no values</li>
  3. </ul>

You can also use for as an alias of each.

while

You can also use while to create a loop:

  1. - var n = 0;
  2. ul
  3. while n < 4
  4. li= n++
  1. <ul>
  2. <li>0</li>
  3. <li>1</li>
  4. <li>2</li>
  5. <li>3</li>
  6. </ul>