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

2

6

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.

Shastashastra answered 21/5, 2015 at 11:40 Comment(1)
Why are you wanting to pass this data inline? I mean why not {{>partial arrayData}}?Evelyne
W
6

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

Wrong answered 23/10, 2015 at 18:21 Comment(0)
B
1

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.

Blessed answered 6/10, 2020 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.