【问题标题】:variables inside underscore.js templateunderscore.js 模板中的变量
【发布时间】:2012-06-23 15:23:20
【问题描述】:

如何在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 是一个 JSON 项(文本字符串)。

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

【问题讨论】:

    标签: javascript underscore.js template-engine


    【解决方案1】:

    您的尝试 2 几乎是正确的,但是您输出编码标题的标签在开头缺少 = 并且不需要字符串中的 +。应该是:

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

    或者你也可以这样做:

    <p><% print(encodedTitle) %></p>
    

    在下划线模板中,您要评估的任何 javascript 都必须包含在 &lt;% %&gt; 中,因此您的第二次尝试只是将 javascript 输出为字符串。您在顶部的示例中正确使用了=,但在尝试 2 中省略了它。

    = 告诉模板引擎将包含的 javascript 的结果作为字符串输出。如果您不使用=,则会执行javascript,但不会输出任何内容。 Underscore 的模板提供了print() 函数作为使用= 的替代方法,我不知道一种方式比另一种方式更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-13
      相关资源
      最近更新 更多