Javascript 使用下划线.js模板计算胡须样式的函数

Javascript 使用下划线.js模板计算胡须样式的函数,javascript,underscore.js,mustache,Javascript,Underscore.js,Mustache,是否可以将下划线.js用于Mustache样式的函数调用?Underline.js提供了一个如何支持胡须语法的示例: _.templateSettings = { interpolate : /\{\{(.+?)\}\}/g }; var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); => "Hello Mustache!" 但是,除了变量mustache.js之外,它还会自动检

是否可以将下划线.js用于Mustache样式的函数调用?Underline.js提供了一个如何支持胡须语法的示例:

_.templateSettings = {
  interpolate : /\{\{(.+?)\}\}/g
};

var template = _.template("Hello {{ name }}!");
template({name : "Mustache"});
=> "Hello Mustache!"
但是,除了变量mustache.js之外,它还会自动检测对象何时是函数,然后对其求值。从mustache.js手册:

var view = {
  title: "Joe",
  calc: function () {
    return 2 + 4;
  }
};

var output = Mustache.render("{{title}} spends {{calc}}", view);
但是,使用下划线.js呈现后者会导致:

var template = _.template("{{title}} spends {{calc}}");
template(view);
"Joe spends function () {
    return 2 + 4;
}"

下划线的模板函数不执行类型检查,总是返回属性/变量的值

但是您可以使用下划线模板求值块来运行javascript函数

因此,您可以执行以下操作:

var template = _.template("<% var spend = calc() %>{{title}} spends {{ spend }}");
var-template=..template(“{{title}}}{{{spend}”);

这显然是在使用默认的ERB风格的求值块,因此,如果您希望使用不同的语法,可以在
\uu.templateSettings
中为
求值
编写自己的正则表达式。

最简单的方法是求值函数,因为下划线允许在模板块中使用任意JavaScript

var template = _.template("{{title}} spends {{calc()}}");

我希望语法与Mustache库保持一致。