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

帅比萌擦擦* 提交于 2019-12-09 11:54:31

问题


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:


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



来源:https://stackoverflow.com/questions/30372693/passing-an-array-of-objects-to-a-partial-handlebars-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!