handlebars array of json object

只谈情不闲聊 提交于 2019-12-17 17:31:37

问题


i need to template with handlebars an array of json object:(by chrome console) [object,object,object,object] where every object is composed by this property:name,surname,ecc.

I've understood that is impossible to put array of object in handlebars but we must create an unique object with all property of all object of array. Can anyone suggest me a function to create it


回答1:


You could set your array as a property of a wrapper object when calling the template.

For example, with objects as the holding property

var an_array = [
    {name: "My name"},
    {name: "Another name"}
];

var source   = /* a template source*/;
var template = Handlebars.compile(source);
var wrapper  = {objects: an_array};

console.log(template(wrapper));

and your template can use this property as follows:

<ul>
    {{#each objects}}
        <li>{{name}}</li>
    {{/each}}
</ul>

And a demo http://jsfiddle.net/YuvNY/1/

var an_array=[
    {name:"My name"},
    {name:"Another name"},    
];

var source   = $("#src").html();
var template = Handlebars.compile(source);
$("body").append( template({objects:an_array}) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v2.0.0.js"></script>

<script type='text/template' id='src'>
<ul>
  {{#each objects}}
      <li>{{name}}</li>
  {{/each}}
</ul>    
</script>

Or you could pass directly the array to the template and call the each helper with the context set to . (a dot)

var template = Handlebars.compile(source);
console.log(template(an_array));
<ul>
    {{#each .}}
        <li>{{name}}</li>
    {{/each}}
</ul>

http://jsfiddle.net/nikoshr/YuvNY/32/

var an_array=[
    {name:"My name"},
    {name:"Another name"},    
];

var source   = $("#src").html();
var template = Handlebars.compile(source);
$("body").append( template(an_array) );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://builds.handlebarsjs.com.s3.amazonaws.com/handlebars-v2.0.0.js"></script>

<script type='text/template' id='src'>
<ul>
  {{#each .}}
      <li>{{name}}</li>
  {{/each}}
</ul>    
</script>


来源:https://stackoverflow.com/questions/11582756/handlebars-array-of-json-object

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