通常,如果您使用 Underscore.js 模板,任何看起来像 <% ... %>
的表达式和 <%= ... %>
由Underscore.js解析
如果我想嵌入文本 <% ... %>
,我该如何转义这样的值?在模板中?
换句话说:我如何告诉 Underscore.js 忽略看起来像占位符但实际上不是占位符的东西?
我想我必须使用某种转义,但通常是 \
不会工作。如果我输入
_.template('<%= name %> ### \<%= name %>', { name: 'foo' });
我得到 foo ### foo
结果,这显然不是我想要的。
更新:为了更清楚,我想从上面的行中得到什么 - 它应该导致
foo ### <%= name %>
最佳答案
如果您的最终输出是 HTML,您可以替换 <
和 >
使用他们的 HTML 转义代码:
_.template('<%= name %> ### <%= name %>', { name: 'foo' });
你也可以 modify Underscore's template settings支持这些东西,这样<%= ... %>
对 Underscore 没有任何意义:
_.templateSettings = {
interpolate: /\{\{(.+?)\}\}/g
};
var t = _.template('{{name}} ### <%= name %>', { name: 'foo' });
关于templates - 在 Underscore.js 模板中使用 <% 而不解析它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14577679/