Passing a function to a Handlebars template

I use (or at least start with) HandlebarsJS for html templates, but maybe I am at a standstill. I want to pass a function to a template, for example.

<div id="divTemplate"> <span onclick="{{func}}">{{text}}</span> </div> 

and then I expect to have something like

 var source = $('#divTemplate').html(); var template = Handlebars.compile(source); var data = { "text": "Click here", "func": function(){ alert("Clicked"); } }; $('body').append(template(data)); 

But the function is executed in init, it is not passed to the template, but the result:

 <span onclick="">Click here</span>. 

I also tried to use some helper functions, but I could not get it to work. Any ideas would be good. :)

+4
source share
1 answer

The solution is pretty simple.

Handlebars will return the properties of the object that you pass to the templates, if the property is a function , it will execute this function and display the return value

In your example, the function does not return any value (it just causes a warning), so the output is empty.

You can create a helper method like this:

 handlebars.registerHelper('stringifyFunc', function(fn) { return new Handlebars.SafeString("(" + fn.toString().replace(/\"/g,"'") + ")()"); }); 

Then, from within the template, you just need to use it for a function that needs to be compressed:

 <div id="divTemplate"> <span onclick="{{stringifyFunc func}}">{{text}}</span> </div> 
+13
source

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


All Articles