Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function into a Handlebars template

I'm using (or at least starting with) HandlebarsJS for the html templates but I might have hit a dead end. What I want is to pass a function to the template, e.g.

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

and then I would 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 on init, it is not passed into the template and the result is:

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

I was trying some stuff with the helper functions as well but I couldn't make it work too. Any ideas would be appreciated. :)

like image 966
isHristov Avatar asked Sep 19 '12 10:09

isHristov


People also ask

How do you call a function in Handlebars?

To call JavaScript function from Handlebars, we can register a helper. to add a template that uses the printItems helper. Then we create the printItems helper and use it by writing: Handlebars.

How do you add templates in your HTML in Handlebars?

Templates The recommended way of adding templates to your page is by including them in <script> tags with a special type. The type attribute is important, otherwise the browser will attempt to parse them as JavaScript (which they are not). The templates have an easy to grasp syntax.

How do you write JavaScript in Handlebars?

Define the template that is packed with handlebars JavaScript syntax. Compile the template with handlebars JavaScript compile method. Provide the data context i.e. data from server-side in a form of JSON to map to the template. Insert or append the final HTML into your designated DOM location of the HTML page.


1 Answers

The solution is pretty straightforward.

Handlebars will output the properties of the object you're passing into the templates, if the property is a function, it will execute the function and output the returned value

In your example the function doesn't return any value (it just calls alert), so the output is empty.

You could create an 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 on the function that needs to be stringified:

<div id="divTemplate">
  <span onclick="{{stringifyFunc func}}">{{text}}</span>
</div>
like image 200
BFil Avatar answered Nov 04 '22 15:11

BFil