Passing a function into a Handlebars template

醉酒当歌 提交于 2019-11-29 04:51:55

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>

You can also make global defined callback function, and pass function calling string in the onclick value in the template.

Note the parenthesis with the tmpCallback for func value in data object.

var tmpCallback = function () {
    alert('hello');
}

var data = {
  "text": "Click here",
  "func": "tmpCallback()"
};

$('body').append(template(data));

This is just a hack for quick workaround, and I think answer by @BFil may be a better one.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!