Question

I'm using Handlebars to display some datas via ajax, and the JSON is like this:

{"data":[
  { "sn":"43","areasn":"3","name":"X1","status":"empty","seats":"12"},
  { "sn":"22","areasn":"1","name":"F1","status":"empty","seats":"8"},
  { "sn":"12","areasn":"2","name":"E1","status":"empty","seats":"6"},
  { "sn":"18","areasn":"3","name":"R3","status":"empty","seats":"6"},
  { "sn":"31","areasn":"1","name":"G4","status":"empty","seats":"4"},
  { "sn":"23","areasn":"2","name":"W5","status":"empty","seats":"12"}
]}

and I need to use handlebars.js in order to display tables in differents areas, something like these:

<script id="tables-template" type="text/x-handlebars-template">
  {{#each data}}
    // All tables in area-1
    <ul id="area-{{areasn}}">
      <li id="{{sn}}">{{name}}</li>
    </ul>

    // All tables in area-2
    <ul id="area-{{areasn}}">
      <li id="{{sn}}">{{name}}</li>
    </ul>

    // All tables in area-3
    <ul id="area-{{areasn}}">
      <li id="{{sn}}">{{name}}</li>
    </ul>
  {{/each}}
</script>

I have no idea how to write a helper for this, is anyone can help? thanks!

Was it helpful?

Solution

There is probably a better way of doing this as I don't know about handlebars, but this should do what you are looking for:

(function() {

    var id = 0,
        cache = [];
        var ids={};  
    Handlebars.registerHelper("groupData", function(data) {
        var dataKey = id++;
        ids[data.areasn]=true;
        if(cache[data.areasn]==undefined)  cache[data.areasn]={id:data.areasn, data:[data]};
        else cache[data.areasn].data.push(data)
        if(dataKey==context.data.length-1){
           context.cache=[];
            for(var i in ids){
                context.cache.push(cache[i])
            } 
        }
    });
})();

var context={"data":[
  { "sn":"43","areasn":"3","name":"X1","status":"empty","seats":"12"},
  { "sn":"22","areasn":"1","name":"F1","status":"empty","seats":"8"},
  { "sn":"12","areasn":"2","name":"E1","status":"empty","seats":"6"},
  { "sn":"18","areasn":"3","name":"R3","status":"empty","seats":"6"},
  { "sn":"31","areasn":"1","name":"G4","status":"empty","seats":"4"},
  { "sn":"23","areasn":"2","name":"W5","status":"empty","seats":"12"}
]}

var template = Handlebars.compile($("#your-template").text());
var html = template(context);
document.body.innerHTML=html;

Check fiddle for html: http://jsfiddle.net/mE49M/226/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top