10

假设我有一个UserJavaScript 模型,看起来像这样:

var User = function(attributes) {
  this.attributes = attributes;
}

User.fields = [
  {name: 'firstName'},
  {name: 'lastName'},
  {name: 'email'}
]

User.prototype.get = function(key) {
  return this.attributes[key];
}

User.all = [new User({firstName: 'Foo'})];

我想通过一个 Handlebars 模板运行它,该模板遍历User类上的每个字段,为其创建一个标题,然后为每个用户呈现值:

<table>
  <thead>
    <tr>
      {{#each User.fields}}
      <th>{{name}}</th>
      {{/each}}
    </tr>
  </thead>
  <tbody>
    {{#each User.all}}
    <tr>
      {{#each User.fields}}
      <td>{{content.get(name)}}</td>
      {{/each}}
    </tr>
    {{/each}}
  </tbody>
</table>

我的问题是,我如何完成内部部分:

{{#each User.fields}}
<td>{{content.get(name)}}</td>
{{/each}}

基本上就是这样做的user.get(field.name)。鉴于我事先不知道这些字段并希望它是动态的,我该如何在 Handlebars 中做到这一点?

谢谢你的帮助。

4

2 回答 2

8
 <body>
   <div id='displayArea'></div>
   <script id="template" type="text/x-handlebars-template">
    <table border="2">
        <thead>
        <tr>
            {{#each Fields}}
             <th>{{name}}</th>
            {{/each}}
        </tr>
        </thead>
        <tbody>
          {{#each users}}
          <tr>
            {{#each ../Fields}}
           <td>{{getName name ../this}}</td>
            {{/each}}
          </tr>
         {{/each}}
        </tbody>
     </table>
 </script>

<script type="text/javascript">
    var User = function(attributes) {
        this.attributes = attributes;
    }

    User.fields = [
        {name: 'firstName'},
        {name: 'lastName'},
        {name: 'email'}
    ]

    User.prototype.get = function(key) {
       return this.attributes[key];
    }

    User.all = [new User({firstName: 'Foo',lastName :'ooF',email : 'foo@gmail.com'}) , new User({firstName: 'Foo2'})];       //array of user

    //handle bar functions to display
    $(function(){
       var template = Handlebars.compile($('#template').html());

        Handlebars.registerHelper('getName',function(name,context){
                          return context.get(name);
          });
        $('#displayArea').html(template({Fields :User.fields,users:User.all}));
    });
   </script>
  </body>  

这将使用车把 JS 中的助手解决您的问题

于 2012-05-23T12:43:33.730 回答
-3

您可以编写一个 Handlebars 助手来为您执行此操作。

于 2012-05-23T05:08:09.000 回答