是否可以使用带有Mustache样式函数调用的underscore.js? 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; }"Is it possible to use underscore.js with Mustache style function calls? The underscore.js manual has an example how to support Mustache syntax:
_.templateSettings = { interpolate : /\{\{(.+?)\}\}/g }; var template = _.template("Hello {{ name }}!"); template({name : "Mustache"}); => "Hello Mustache!"However, apart from variables mustache.js also automatically detects when the object is a function and then evaluates it. From the mustache.js manual:
var view = { title: "Joe", calc: function () { return 2 + 4; } }; var output = Mustache.render("{{title}} spends {{calc}}", view);However, using underscore.js to render the latter results in:
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
但是您可以使用下划线模板evaluate块来运行javascript函数。
所以你可以做到以下几点:
var template = _.template("<% var spend = calc() %>{{title}} spends {{ spend }}");这显然是使用默认的ERB样式评估块,所以如果您更愿意使用不同的语法,请_.templateSettings在_.templateSettings编写自己的regex进行evaluate 。
Underscore's template function doesn't perform type checking and always returns the value of the property/variable.
https://github.com/documentcloud/underscore/blob/master/underscore.js#L1161
But you can use the underscore template evaluate block to run javascript functions.
So you can do the following:
var template = _.template("<% var spend = calc() %>{{title}} spends {{ spend }}");That's obviously using the default ERB-style evaluation block, so feel free to write your own regex for evaluate in _.templateSettings if you'd rather use a different syntax.
更多推荐
发布评论