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.

1
  • 2
    Why are you wanting to pass this data inline? I mean why not {{>partial arrayData}}? Commented May 21, 2015 at 15:14

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.