I would like to use handlebars.js or mustache.js to iterate over a list of families, and then iterate over that family's members. Inside of both loops, I want to display properties of both. However, once I get into the second iteration, none of the family variables are visible.
{{#each families}} {{#each members}} <p>{{ ( here I want a family name property ) }}</p> <p>{{ ( here I want a member name property ) }}</p> {{/each}} {{/each}}
Is this possible? I'd greatly appreciate any help!
Handlebars. js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars. js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be; Mustache: Logic-less templates.
Handlebars. js has a broader approval, being mentioned in 643 company stacks & 175 developers stacks; compared to Pug, which is listed in 174 company stacks and 119 developer stacks.
EJS is way faster than Jade and handlebars. EJS has a really smart error handling mechanism built right into it. It points out to you, the line numbers on which an error has occurred so that you don't end up looking through the whole template file wasting your time in searching for bugs.
It works by expanding tags in a template using values provided in a hash or object. We call it "logic-less" because there are no if statements, else clauses, or for loops. Instead there are only tags. Some tags are replaced with a value, some nothing, and others a series of values.
Sorry I'm a little late in the game here. The accepted answer is great but I wanted to add an answer that I think is also useful, especially if you are iterating over simple row/column arrays.
When you're working with nested handlebar paths, you can use ../
to refer to the parent template context (see here for more information).
So for your example, you could do:
{{#each families}} {{#each members}} <p>{{../surname}}</p> <p>{{given}}</p> {{/each}} {{/each}}
This was especially useful for me because I was making a grid and I wanted to give each square a class name corresponding to its row and column position. So if rows
and columns
, simply return arrays, I can do this:
<tbody> {{#each rows}} <tr> {{#each columns}} <td class="{{this}}{{../this}}"></td> {{/each}} </tr> {{/each}} </tbody>
Update
This solution is for Handlebars. A comment below explains why it will not work in Mustache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With