Подтвердить что ты не робот

Как вы интерполируете динамическое {{property}} в Handlebars/Ember.js?

Скажем, у меня есть модель User в 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'})];

И я хочу запустить его через шаблон 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, учитывая, что я не знаю полей перед рукой и хочу, чтобы это было динамическим?

Спасибо за вашу помощь.

4b9b3361

Ответ 1

 <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 : '[email protected]'}) , 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>  

Это решит проблему ur с помощью помощников в ручке JS

Ответ 2

Вы можете написать помощник Handlebars, чтобы сделать это для вас.