How to use getters in handlebars.js templates?

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

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

Obviously this does not work. Does handlebars.js have any syntax that would allow getters to be used, as shown above?

Thanks.

+4
source share
3 answers

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

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

0
source

This works in the helm, in the main 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>'); 
0
source

And better, but time is tuned by the rudder compiler. The following code should be added to scripts that use use to compile your templates, not run-time. add this code to your compilation code, not at runtime - this is not an assistant). Then you can simply write {{model.title}}, and this expression will be automatically translated into model.get ('title') by the compiler. Of course, if the "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 + '\'])'; } }; 
0
source

Source: https://habr.com/ru/post/1399409/


All Articles