简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM