Search code examples
javascripthandlebars.jsmustache

Make a for-each with Mustache?


Im trying to learn Mustache, but cant get this script to work, and the guides i have found on Google dont seem to cover this one.

<div id="test"> </div>
<script id="testtpl" type="text/template">
    {{#sheet}}
      {{#.}}    
        {{a}}
      {{/.}}
    {{/sheet}}         
</script>

<script>
  var testing = {
    sheet: {
      'fur': {a: 6, b: 2, item: ['bold']},
      'bur': {a: 6, b: 2, item: ['bold']}
    }
  };
  $(function() {
    var template = $('#testtpl').html();
    var html = Mustache.to_html(template, testing);
    $('#test').html(html);
  });
</script>

Solution

  • I think you want something like this

    Handlebars Template

    {{#eachProp sheet}}
      {{this}}
    {{/eachProp}}
    

    Context or javascript Literal

    {
        sheet: {
          'fur': {a: 1, b: 2, item: ['bold']},
          'bur': {a: 5, b: 2, item: ['bold']}
        }
    }
    

    Handlebars Helper

    Handlebars.registerHelper('eachProp', function(context, options) {
      var data,
        out = [];
    
       console.log(context);
    
       for (var key in context) {
         out.push(context[key].a);
       }
    
       out = out.join(',');
    
      return out;
    });
    

    Try these blocks on Try Handlebars. Now play around with this on the site and get whatever you want. Hope this helps!!