使用下划线模板的八字胡样式函数求值

Mustache style function evaluation with underscore.js template

本文关键字:样式 函数 八字胡 下划线      更新时间:2023-09-26

是否可以使用underscore.js与Mustache风格的函数调用?underscore.js手册中有一个如何支持Mustache语法的示例:

_.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);

但是,使用underscore.js来呈现后者会导致:

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

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

https://github.com/documentcloud/underscore/blob/master/underscore.js L1161

但是你可以使用下划线模板计算块来运行javascript函数。

所以你可以这样做:

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

这显然是使用默认的erb风格的计算块,所以如果你宁愿使用不同的语法,可以自由地为evaluate_.templateSettings中编写自己的正则表达式。

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

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