使用underscore.js模板评估小胡子样式函数(Mustache style function evaluation with underscore.js template)

编程入门 行业动态 更新时间:2024-10-22 21:41:35
使用underscore.js模板评估小胡子样式函数(Mustache style function evaluation with underscore.js template)

是否可以使用带有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.

更多推荐

本文发布于:2023-08-07 12:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1464246.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:小胡子   样式   函数   模板   underscore

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!