pug

Concatenate a variable inside an ID attribute in Pug


I'm trying to create incrementing id attributes using variable interpolation in a loop.

ul
  - for(var i = 0; i < 3; i++) 
    li#id#{i}

I expected to get the below, but it doesn't work.

li#id0
li#id1
...

Solution

  • Pug's id shorthand doesn't work with dynamic values. Use the standard attribute syntax instead.

    ul
      - for (var i = 0; i < 3; i++) 
        li(id= 'id' + i)
    

    Or, if you like ES6 template strings:

    ul
      - for (var i = 0; i < 3; i++) 
        li(id=`id${i}`)
    

    Both compile to:

    <ul>
      <li id="id0"></li>
      <li id="id1"></li>
      <li id="id2"></li>
    </ul>