سؤال

I'm trying to get my handlebars.js template to do something like this:

<li>{{ user.get('firstName') }} {{ user.get('lastName') }}</li>   

Obviously though, that's not working. Does handlebars.js have any syntax which would allow using getters directly like above?

Thanks.

هل كانت مفيدة؟

المحلول

<li>{{user.firstName}} {{user.lastName}}</li>

Although if it's in a loop (assumption from <li>) it should be {{this.firstname}}

نصائح أخرى

This is working in handlebars, basicallya helper and then use {{get book "title"}}:

Handlebars.registerHelper('get', function(model, attributeName) 
{
    return model.get(attributeName); 
});

var templateStr = '<div class="book-title">{{get preferredBook "title"}}</div>'; 

var Book = Backbone.Model.extend({});
var b = new Book({title: 'Lord of the rings'});
var context = {
    preferredBook: b
}; 

var template = Handlebars.compile(templateStr);

var output = template(context);
expect(output).toBe('<div class="book-title">Lord of the rings</div>');

And better, but time time customizing the handlebars compiler. The following code needs to be added in the script that use use to COMPILE your templates, not at runtime. add this code into your compilation code, not runtime - this is not a helper). Then you can just write {{model.title}} and that expression will be translated into model.get('title') automatically by the compiler. Of course, if 'model' is not a Backbone.Model then it will access the json property as usual.

Handlebars.JavaScriptCompiler.prototype.nameLookup = function(parent, name)
{
    var result = '((typeof(Backbone)!="undefined" && ' + parent + ' instanceof Backbone.Model) ? ' + parent + '.get("' + name + '") : ' + parent;
    if (/^[0-9]+$/.test(name))
    {
        return result + '[' + name + '])';
    }
    else if (Handlebars.JavaScriptCompiler.isValidJavaScriptVariableName(name))
    {
        return result + '.' + name + ')';
    }
    else
    {
        return result + '[\'' + name + '\'])';
    }
};
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top