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

后端 未结 6 1814
后悔当初
后悔当初 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 01:57

    Great answer @maxbeatty.

    I just wanted to add another example if anyone have the same problem and can't understand the above solution.

    First I have one dimensional array which I wanted to split on every 4 elements:

    // this is the one dimensional data we have from let's say a mysql query
    var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', ...];
    
    // think of it as [[], [], [], [], [], ...]
    // but instead we'll be adding a dummy object with a dummyKey
    // since we need a key to iterate on
    var jagged = [];
    
    var size = 4, // this is the size of each block
        total = array.length / block; // total count of all blocks
    // slice the initial one dimensional array into blocks of 4 elements each
    for (var i=0; i < total; i++) {
        jagged.push({dummyKey: array.slice(i*size, (i+1)*size)});
    }
    

    Now if we pass jagged into our view we can iterate it like that:

      {{#jagged}}
      • {{#dummyKey}}
      • {{.}}
      • {{/dummyKey}}
    • {{/jagged}}

    If we have our initial array filled with objects:

    var array = [{key1: 'a', 
                  key2: 'b'},
                 {key1: 'c', 
                  key2: 'd'},
                 {key1: 'e', 
                  key2: 'f'},
                  ...
    ];
    

    Then in our template we'll have:

      {{#jagged}}
      • {{#dummyKey}}
      • {{key1}} - {{key2}}
      • {{/dummyKey}}
    • {{/jagged}}

提交回复
热议问题