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

后端 未结 6 1799
后悔当初
后悔当初 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:08

    You can nest sections easily with lists of objects. Use a data structure where families is a list that has an object members that has a list of any objects (or even more lists)like:

    {
      "families" : [
            {
              "surname": "Jones",
              "members": [
                {"given": "Jim"},
                {"given": "John"},
                {"given": "Jill"}
              ]
            },
            {
              "surname": "Smith",
              "members": [
                {"given": "Steve"},
                {"given": "Sally"}
              ]
            }
          ]
    }
    

    You would be able to populate a template like:

      {{#families}}
    • {{surname}}
        {{#members}}
      • {{given}}
      • {{/members}}
    • {{/families}}

    jsFiddle is currently down so here's the full working HTML with JS:

    
    
    
      
      
      
    
    
    
    

提交回复
热议问题