Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

javascript - 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. :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...