2014-10-22 30 views
0

我想呈現模型對象內的每個數組值。我可以設法渲染數組的第一個值,但不能渲染其餘的數組。我試過在每個函數中工作,但不起作用。我需要查看每一行中的所有數組值。請檢查的例子,你很快就會看到:Handlebars - 如何將數組內的所有值呈現給模板模型?

Here is working sample which renders only first value of the array: http://jsfiddle.net/N2b5M/1123/

When i try to render all the dates inside tags array with each, i won't work: http://jsfiddle.net/N2b5M/1136/

模板:

{{#users}} 
    <tr> 
     <td>{{fullName person}}</td> 
     <td>{{jobTitle}}</td> 
     <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 
     <td>{{currentDate}}</td> 
    </tr> 
{{/users}} 

數據:

var data = { 
    users: [ { 
     person: { 
      firstName: "Garry", 
      lastName: "Finch", 
      tags: [ 
       { 
        "type": "P", 
        "date": "10.9.2014" 
       }, 
       { 
        "type": "C", 
        "date": "18.12.2014" 
       }, 
       { 
        "type": "T", 
        "date": "2.10.2014" 
       } 
      ] 
     }, 
     jobTitle: "Front End Technical Lead", 
     twitter: "gazraa" 
    }, { 
     person: { 
      firstName: "Garry", 
      lastName: "Finch", 
      tags: [ 
       { 
        "type": "T", 
        "date": "2.11.2014" 
       } 
      ] 
     }, 
     jobTitle: "Photographer", 
     twitter: "photobasics" 
    }, { 
     person: { 
      firstName: "Garry", 
      lastName: "Finch", 
      tags: [ 
       { 
        "type": "T", 
        "date": "11.12.2014" 
       } 
      ] 
     }, 
     jobTitle: "LEGO Geek", 
     twitter: "minifigures" 
    } ] 
}; 

的javascript:

var source = $("#some-template").html(); 
var template = Handlebars.compile(source); 

Handlebars.registerHelper('fullName', function(person) { 
    return person.firstName + " " + person.lastName; 
}); 

Handlebars.registerHelper('currentDate', function(context) { 
    var currentTag = this.person.tags[0]; 
    var currentDate = currentTag.date; 
    return currentDate; 
}); 

$('body').append(template(data)); 

我試圖使所有標籤陣列內的日期,並試圖像這樣:

{{#each person.tags}} 
     <td>{{currentDate}}</td> 
{{/each}} 

Handlebars.registerHelper('each', function(context, options) { 
    var tagsTotal = context.person.tags.length; 
    var ret = ''; 
    console.log(tagsTotal); 
    for(i = 0; i < tagsTotal; i++) { 
     var tagType = context.type; 

     ret += options.fn(context[i]); 
    } 
    return ret; 
}); 

回答

2

我不知道這是否是醜陋的,或者是有更好的做法。但這個作品:

<h1>Handlebars JS Example</h1> 
<script id="some-template" type="text/x-handlebars-template"> <table> 
    <thead> 
     <th>Name</th> 
     <th>Job Title</th> 
     <th>Twitter</th> 
     <th>Dates</th>   
    </thead> 
    <tbody> 
     {{#users}} 
     <tr> 
      <td>{{fullName person}}</td> 
      <td>{{jobTitle}}</td> 
      <td><a href="https://twitter.com/{{twitter}}">@{{twitter}}</a></td> 

      {{#person}} 
       {{#tags}} 
        <td> 
         {{date}} 
        </td> 

       {{/tags}} 

      {{/person}} 
     </tr> 
     {{/users}} 
    </tbody> 
</table> 
</script> 
+0

+1從我,非常感謝你的隊友(: – 2014-10-22 13:17:03

相關問題