underscore.js模板中的变量

17
如何在使用 backbone.js 构建的应用程序中,在 underscore.js 模板中设置变量?我只想创建可重用的处理字符串。此外,可以使用 _.escape 等内置函数来处理这些变量吗?
<script type="text/html" id="templateresults">

<p><%= encodeURIComponent(title) %></p> // this works

// try 1:
var encodedTitle = encodeURIComponent(title); // shows up as regular text
<p>'+encodedTitle+'</p> // this doesn't work and shows up as regular text

// try 2:
<% var encodedTitle = encodeURIComponent(title); %> // nothing shows up
<p><% '+encodedTitle+' %></p> // nothing shows up

</script>

title 是一个 JSON 项(文本字符串)。

编码输出:This%20is%20a%20Sample%20Title
常规输出:This is a Sample Title

1个回答

23

你的尝试2基本正确,但输出encodedTitle的标签缺少开头的=,并且字符串中不需要+。应该是这样的:

<p><%= encodedTitle %></p>

或者您还可以这样做:

<p><% print(encodedTitle) %></p>
在underscore模板中,任何您希望执行的JavaScript代码都必须包含在<% %>内,这就是为什么您的第二次尝试只会将javascript输出为字符串的原因。您在顶部的示例中正确地使用了=,但在第二次尝试中省略了它。 =告诉模板引擎将封闭的JavaScript代码的结果作为字符串输出。如果不使用=,则会执行JavaScript代码,但不会输出任何内容。Underscore的模板提供了print()函数作为使用=的替代方法,我不知道哪种方式更好。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接