handlebars array of json object

后端 未结 1 374
悲&欢浪女
悲&欢浪女 2020-12-12 20:24

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

1条回答
  •  旧巷少年郎
    2020-12-12 20:57

    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:

      {{#each objects}}
    • {{name}}
    • {{/each}}

    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}) );
    
    
    
    


    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));
    
      {{#each .}}
    • {{name}}
    • {{/each}}

    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) );
    
    
    
    

    0 讨论(0)
提交回复
热议问题