javascripthtmlpugpugjs

How to pass for loop variable value in a class of a anchor tag in PUG template engine?


I am trying to print <a> tag 5 times by using PUG template engine.

I want my code like it is below. Where I just want two classe item and item-1,2,3 etc.

HTML code: desired result

<a class="item item-1" href="#">1  Item</a><br/>
<a class="item item-2" href="#">2  Item</a><br/>
<a class="item item-3" href="#">3  Item</a><br/>
<a class="item item-4" href="#">4  Item</a><br/>

I am using this code now which is below and working fine

PUG code

- for (var x=1; x < 6; x++)
    a.item.item-(href='#') #{x}  Item
    br

Which output in HTML is below and #{x} variable to printing fine

<a class="item item-" href="#">1  Item</a><br/>
<a class="item item-" href="#">2  Item</a><br/>
<a class="item item-" href="#">3  Item</a><br/>
<a class="item item-" href="#">4  Item</a><br/>
<a class="item item-" href="#">5  Item</a><br/>

But when I am using #{x} variable like below it is showing error

- for (var x=1; x < 6; x++)
    a.item.item-#{x}(href='#') #{x}  Item
    br

Error

Pug:2:17
    1| - for (var x=1; x < 6; x++)
  > 2|     a.item.item-#{x}(href='#') #{x}  Item
-----------------------^
    3|     br

Unexpected token `interpolation` expected `text`, `interpolated-code`, `code`, `:`, `slash`, `newline` or `eos`

I am aware that we use # for ID but why it is not printing value of x after item- in class?


Solution

  • I've managed to get your desired result by changing the code as specified in Pug's documentation:

    - for (var x=1; x < 6; x++)
        a(class='item item-'+x)(href='#') #{x}  Item
        br
    

    Codepen: https://codepen.io/anon/pen/YrqBdY