2

there is already an answer here Iterating over basic β€œfor” loop using Handlebars.js but it's from 2012 so maybe I can get a better solution now.

I want to loop n times. If there are 5 containers to create I want to loop 5 times.

I render my template with NodeJs and try to pass a count variable

res.render('myTemplate', {
   barCount: 3
});

Currently I have to write

<div class="container">
</div>
<div id="bar3" class="bar"></div>

<div class="container">
</div>
<div id="bar2" class="bar"></div>

<div class="container">
</div>
<div id="bar1" class="bar"></div>

But I would like to write something like this

    {{#each barCount}}
        <div class="container"></div>        
        <div id="bar{{barCount - this + 1}}" class="bar"></div>
    {{/each}}

Do I still have to use a helper?

peterHasemann
  • 1,410
  • 2
  • 15
  • 41

1 Answers1

1
res.render('myTemplate', {
  barCount: [3, 2, 1] // or use lodash range function
});

{{#each barCount}}
    <div class="container"></div>        
    <div id="bar{{this}}" class="bar"></div>
{{/each}}
danday74
  • 38,089
  • 29
  • 169
  • 214