Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

handlebars.js - handlebars array of json object

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...