templates - 在 Underscore.js 模板中使用 <% 而不解析它

标签 templates underscore.js

通常,如果您使用 Underscore.js 模板,任何看起来像 <% ... %> 的表达式和 <%= ... %>由Underscore.js解析

如果我想嵌入文本 <% ... %>,我该如何转义这样的值?在模板中?

换句话说:我如何告诉 Underscore.js 忽略看起来像占位符但实际上不是占位符的东西?

我想我必须使用某种转义,但通常是 \不会工作。如果我输入

_.template('<%= name %> ### \<%= name %>', { name: 'foo' });

我得到 foo ### foo结果,这显然不是我想要的。

更新:为了更清楚,我想从上面的行中得到什么 - 它应该导致

foo ### <%= name %>

最佳答案

如果您的最终输出是 HTML,您可以替换 <>使用他们的 HTML 转义代码:

_.template('<%= name %> ### &lt;%= name %&gt;', { 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/

相关文章:

c++ - 将抽象类(仅限纯虚函数)的继承/派生限制在某个类

javascript - 如何在更新数据库记录时使用 $watch 查看更改

javascript - 主干清理 - 删除上下文绑定(bind)回调的引用

javascript - 如何在 "javascript class"中重新定义一个方法

javascript - .apply 到底是做什么的?

c++ - 指向模板类的指针

django - 如何在 Django 模板中指定 URL?

c++11 如何将遗留类转换为模板

c++ - 使用 std::remove_if() 时没有可行的重载 '='

node.js - 使用 mongoose 在 mongodb 上执行 mapreduce 时不能在 reduce 函数中使用 underscore.js