将功能传递到Handlebars模板中 [英] Passing a function into a Handlebars template

查看:79
本文介绍了将功能传递到Handlebars模板中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 HandlebarsJS 作为html模板,但我可能会遇到死胡同。我想要的是将一个函数传递给模板,例如

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

然后我希望能有类似的内容

  var source = $('#divTemplate')。html(); 
var template = Handlebars.compile(source);

var data = {
text:Click here,
func:function(){
alert(Clicked);
}
};

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

但是该函数在init中执行,它不会被传递到模板中,结果是:

 < span onclick =>点击此处< / span> ;. 

我正在尝试一些辅助函数,但我无法使其工作。任何想法,将不胜感激。 :)

解决方案

这个解决方案非常简单。

如果属性是 函数 ,则输出要传递到模板中的对象的属性,将执行该函数,输出返回的值



在你的例子中,函数不返回任何值(它只是调用alert),所以输出为空。 p>

你可以像这样创建一个辅助方法:

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

然后从模板中只需要使用它在需要字符串化的函数上:

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


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

解决方案

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>

这篇关于将功能传递到Handlebars模板中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆