Javascript – How to interpolate a dynamic {{property}} in Handlebars / Ember.js

handlebars.jsjavascript

Say I have a User model in JavaScript that looks something like this:

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

And I want to run it through a Handlebars template that goes through each field on the User class, creates a header for it, and then for each user renders the values:

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

My question is, how do I accomplish that internal part:

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

That's basically doing user.get(field.name). How can I do that in Handlebars, given I don't know the fields before hand and want this to be dynamic?

Thanks for your help.

Best Answer

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

This will solve ur problem using helpers in handlebar JS