Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Javascript function from handlebar

How can I call a JavaScript function from inside a handlebars script? Reason:

I wasn't able to break the {{#each}} from inside handlebars. So I need to pass it to JavaScript to do the logic.

like image 372
Venkatesh K Avatar asked Feb 18 '14 06:02

Venkatesh K


People also ask

Can you use JavaScript in Handlebars?

js and the <script> Element. An HTML <script> element with type value of text/x-handelbars-template can be used to contain Handlebars. js template text and expressions. This allows writing Handlebars.

What is helper in Handlebars?

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


2 Answers

You can do that with helpers;

Handlebars.registerHelper("printItems", function(items) {   var html = "<ul>";   items.forEach(function(entry) {     html += "<li>" + entry + "</li>";   });   html += "</ul>";   return html; }); 

and in your handlebars template;

{{printItems items}} 

Above code will put your items in list.

For more details refer here. Go to helpers section

like image 116
Hüseyin BABAL Avatar answered Sep 22 '22 17:09

Hüseyin BABAL


Handlebars is a minimal tempting language for JavaScript and as such it will not let you execute arbitrary code from within a template. Handlebars does however provide you with helpers let you execute pre-defined code over your template. The built in ones are: each, unless, if and else.

You can create your own helpers with the Handlebars.registerHelper method. Here is a simple example that formats a phone number. So long as you register the helper before you call it you should be able to use {{formatPhoneNumber phoneNumber}} anywhere in your code.

Handlebars.registerHelper("formatPhoneNumber", function(phoneNumber) {   phoneNumber = phoneNumber.toString();   return "(" + phoneNumber.substr(0,3) + ") " +      phoneNumber.substr(3,3) + "-" +      phoneNumber.substr(6,4); }); 

Note: While it may be technically possible to execute non-rendering code from within a helper, this is considered bad practice and should be avoided if at all possible.

like image 42
Baer Avatar answered Sep 26 '22 17:09

Baer