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.
const source = $("#some-template"). html(); const template = Handlebars. compile(source); const data = { items: ['foo', 'bar'] } $('div'). append(template(data));
The {{concat}} helper is designed to concatenate and link multiple things together. The {{concat}} helper will take all of the items passed to it, treat them as strings, and concatenate them together without any spaces. There can be an unlimited amount of items passed to the helper.
A Handlebars helper call is a simple identifier, followed by zero or more parameters (separated by a space). Each parameter is a Handlebars expression that is evaluated exactly the same way as described above in "Basic Usage": template {{firstname}} {{loud lastname}}
<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>
This will solve ur problem using helpers in handlebar JS
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With