javascript 将函数传递给 Handlebars 模板

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12492701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:19:28  来源:igfitidea点击:

Passing a function into a Handlebars template

javascripthandlebars.js

提问by isHristov

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

我正在为 html 模板使用(或至少开始使用)HandlebarsJS,但我可能已经走到了死胡同。我想要的是将一个函数传递给模板,例如

<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:

但是函数是在 init 上执行的,它没有传入模板,结果是:

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

我也在尝试一些带有辅助函数的东西,但我也无法让它工作。任何想法,将不胜感激。:)

回答by BFil

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

Handlebars 将输出您传递到模板中的对象的属性,如果该属性是一个函数它将执行该函数并输出返回值

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>

回答by Satys

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

您也可以制作全局定义的回调函数,并在模板中的onclick 值中传递函数调用字符串。

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

请注意数据对象中 func 值的 tmpCallback 括号。

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.

这只是一种快速解决方法的技巧,我认为@BFil 的回答可能更好。