Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of objects to a partial - handlebars.js

Im trying to pass an array of objects into a partial as an argument:

{{> partial [{title: "hello", year: "2015"}, {title: "hello2" year: "2015"}] }}

and then on the partial:

<div>

  {{#each this}}
    <label>{{title}}</label>
    <label>{{year}}</label>
  {{/each}}

</div>

... but nothing shows up.

Is there a way to pass array data to a partial? Thanks in advance.

like image 568
Perry Avatar asked May 21 '15 11:05

Perry


2 Answers

Create a helper that parses the JSON and wrap your partial with this context.

Template:

{{#getJsonContext '[{"title": "hello", "year": "2015"}, {"title": "hello2" "year": "2015"}]'}}
    {{> partial this }}
{{/getJsonContext}}

Note that the names are quoted as well as the values in the JSON string.

Helper:

Handlebars.registerHelper('getJsonContext', function(data, options) {
   return options.fn(JSON.parse(data));
});

Credit: https://github.com/assemble/assemble/issues/228#issuecomment-20853985

like image 97
switang Avatar answered Sep 23 '22 13:09

switang


This should work

{{> partial items=this.something }}

in

Handlebars.registerPartial(
    'partial', 
    "<div>{{#each items}}<label>{{title}}</label><label>{{year}}</label>{{/each}}</div>"
);

input:

{
    something: [{title: "hello", year: "2015"}, {title: "hello2", year: "2015"}]
}

Also, there is a problem in the JSON object.

like image 42
Akku Avatar answered Sep 21 '22 13:09

Akku