我四处寻找,但找不到真正有效的。
在 Mustache 中,当你抛出 2 个 curly 时,里面的字符串将会被转义,如果你抛出 3 个,则不会。
// when you pass {foo: '"bar"'} as hash, the following template will be:
{{foo}} // => "bar"
{{{foo}}} // => "bar"
对吗?所以我创建了以下内容。
http://jsfiddle.net/beatak/6s5PU/
这显示了插值和转义相反,意味着 2 curly 表示未转义 3 表示转义。当我在 _.templateSettings
中的 escape
和 interpolate
之间切换时,它不起作用。为什么?下划线模板优先于这三个(escape
、interpolate
和 evaluate
)?
我知道我现在忽略了 jsfiddle 上的evaluate
,如果它们一起工作那就太棒了,但现在,我想让 2 和 3 curl 工作得很好......
最佳答案
搜索转义的正则表达式,然后进行插值,然后求值。这就是为什么转义形式 {{ }}
在未转义形式 {{{ }}}
之前匹配。您可以在 _.template
的源代码中自行更改顺序。
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
更改以上行的顺序将更改优先级。
如果您不想更改下划线优先级,可以使用更复杂的转义正则表达式。没有消极的后视是很棘手的,但我想出了:
/\{\{([^\{\}]+?)(?!\}\}\})\}\}/
这应该意味着:{{
,后跟一个或多个非大括号字符,后面不得跟三大括号(}}}
),后跟双大括号 }}
。它适用于您的 fiddle ,希望对您有用。
关于javascript - underscore.template 的 _.templateSettings 的正确 mustache 模板配置是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14267191/