下划线模板 - 更改令牌标记 [英] Underscore templating - changing token markers
问题描述
开箱即用的下划线模板使用标记 <%= %>
表示原始内容,<%- %>
表示 HTML 转义内容.
我知道您可以使用以下方法更改标记:
_.templateSettings.interpolate =/\{\{(.+?)\}\}/g;
但这与原始内容和转义内容有何关系?在我看来,您最终只有一种类型的标记.还是我忽略了什么?
Underscore.js 文档 说明了这一点(强调):
<块引用>如果 ERB 样式的分隔符不是您的菜,您可以更改 Underscore 的模板设置以使用不同的符号来衬托内插代码.定义一个内插正则表达式来匹配应该逐字插入的表达式,一个转义正则表达式来匹配应该在 HTML 转义后插入的表达式,以及一个评估正则表达式来匹配应该被评估而不插入到结果字符串.
所以你可以给 _.templateSettings
对象一个 escape
属性:
_.templateSettings.escape =/\{\{-(.*?)\}\}/g
<预><代码>>>>编译 = _.template("转义:{{- value }}\n未转义:{{ value }}")>>>编译({值:'你好,<b>世界!</b>'})逃脱:你好,<b>世界!</b>没有逃脱:你好,世界!"
Out of the box underscore templating uses the markers <%= %>
for raw, and <%- %>
for HTML escaped content.
I know you can change the markers using something like:
_.templateSettings.interpolate = /\{\{(.+?)\}\}/g;
But how does this relate to raw and escaped content? It looks to me like you end up with only one type of marker. Or have I overlooked something?
The Underscore.js documentation says this (emphasis added):
If ERB-style delimiters aren't your cup of tea, you can change Underscore's template settings to use different symbols to set off interpolated code. Define an interpolate regex to match expressions that should be interpolated verbatim, an escape regex to match expressions that should be inserted after being HTML escaped, and an evaluate regex to match expressions that should be evaluated without insertion into the resulting string.
So you can just give the _.templateSettings
object an escape
property:
_.templateSettings.escape = /\{\{-(.*?)\}\}/g
>>> compiled = _.template("Escaped: {{- value }}\nNot escaped: {{ value }}")
>>> compiled({value: 'Hello, <b>world!</b>'})
"Escaped: Hello, <b>world!</b>
Not escaped: Hello, <b>world!</b>"
这篇关于下划线模板 - 更改令牌标记的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!