簡體   English   中英

如何在Handlebars / Ember.js中插入動態{{property}}?

[英]How do you interpolate a dynamic {{property}} in Handlebars / Ember.js?

假設我在JavaScript中有一個User模型,看起來像這樣:

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中做到這一點,因為我不知道前面的字段並希望這是動態的?

謝謝你的幫助。

 <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中使用助手的問題

您可以編寫一個Handlebars幫助程序來為您執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM