javascript underscore.js 模板中的变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11170655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
variables inside underscore.js template
提问by Steve
How to set up variables inside an underscore.js
template for an app built with backbone.js
? I just want to create reusable processed strings. Also, can underscore.js
's built-in functions like _.escape
be used to process those variables?
如何在underscore.js
模板中为使用 构建的应用程序设置变量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
is a JSON item (text string).
title
是一个 JSON 项目(文本字符串)。
Encoded output: This%20is%20a%20Sample%20Title
Regular output: This is a Sample Title
编码输出:This%20is%20a%20Sample%20Title
常规输出:This is a Sample Title
回答by Endophage
Your try 2 is almost right but the tag where you output encodedTitle is missing the =
at the start and doesn't need the +
in the string. Should be:
您的 try 2 几乎是正确的,但是您输出 encodingTitle 的标签在开头缺少=
并且不需要+
字符串中的 。应该:
<p><%= encodedTitle %></p>
Alternatively you could also do:
或者你也可以这样做:
<p><% print(encodedTitle) %></p>
In underscore templates, any javascript you want evaluated must be contained inside <% %>
, hence why your second attempt just outputs the the javascript as a string. You correctly used the =
in your sample at the top but omitted it in try 2.
在下划线模板中,您要评估的任何 javascript 都必须包含在 中<% %>
,因此您的第二次尝试只是将 javascript 输出为字符串。您=
在顶部的示例中正确使用了,但在尝试 2 中省略了它。
The =
tells the templating engine to output the result of the enclosed javascript as a string. If you don't use the =
, the javascript is executed, but nothing is output. Underscore's templates provide the print()
function as an alternative to using the =
, I dont know that one way is better than the other.
该=
告诉模板引擎输出封闭的javascript作为字符串的结果。如果不使用=
,则执行 javascript,但不输出任何内容。Underscore 的模板提供了该print()
功能作为使用 的替代方法=
,我不知道一种方式比另一种方式更好。