handlebars.js #each array. Use first item as a headline?

I have the following data:

var test = [];
test.push({typ: 'a', name="bur"});
test.push({typ: 'a', name="fur"});
test.push({typ: 'b', name="kok"});
test.push({typ: 'b', name="bur"});

Im rendering that with handlebars.js, and use it in this template:

{{#each .}}
  <div>
  <div>{{ name }}</div>
  </div> 
{{/each}}

That works fine, but i want to put "typ" as a headline on it like this:

<div class="head">a</div>
<div class="name">bur</div>
<div class="name">fur</div>
<div class="head">b</div>
<div class="name">kok</div>
<div class="name">bur</div>

But how do i do that?

Upvotes: 0

Views: 1065

Answers (2)

PSL
PSL

Reputation: 123749

Why not transform your object and do it this way:

JS:

var postProcessed = {};

test.forEach(function(val){ //Look for support of forEach you can just use for loop for older browser support if you are running this on the browser (Node should be fine).
    postProcessed[val.typ] = postProcessed[val.typ] || [];
    postProcessed[val.typ].push(val.name);
});
//{"a":["bur","fur"],"b":["kok","bur"]} 

Template:

{{#each .}}
     <div class="head">{{ @key }}</div>
     {{#each .}}
          <div class="name">{{ this }}</div>
     {{/each}}
{{/each}}

Demo

You cannot do too many things in Handlebars (though you have handlebar helpers and add your own helper). I would suggest you to try to make your modal and template adjusted and mostly in a one-one fashion.

Upvotes: 2

Simon Boudrias
Simon Boudrias

Reputation: 44669

This is not a direct answer, but I think it'd be cleaner to setup your CSS this way:

div {
  /* Header style */
}

div ~ div {
  /* normal style */
}

The Handlebars solution would be to use the special value {{@index}} (or @key for objects) inside the loop to access the index and set style accordingly. (But this is a lot of overhead because Handlebars is logic less, so you'd probably need to create a helper ifEqual0 or something like that...)

The cleaner way when using Handlebars would be to separate your array as header and items and passing that as argument to the template.

Upvotes: 0

Related Questions