How do I use nested iterators with Mustache.js or Handlebars.js?

后端 未结 6 1815
后悔当初
后悔当初 2020-12-24 01:52

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 pr

6条回答
  •  难免孤独
    2020-12-24 02:13

    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}}
        

    {{../surname}}

    {{given}}

    {{/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:

    
      {{#each rows}}                                                           
        
          {{#each columns}}
            
          {{/each}}
        
      {{/each}}
    
    

    Update

    This solution is for Handlebars. A comment below explains why it will not work in Mustache.

提交回复
热议问题