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