使用Underscore.js模板的Rails

22

我试图在一个没有jammit作为asset packager的Rails 2.3应用程序中使用underscore.js模板进行模板化。

这是简单的模板:

<script type="text/template" id="q-template">
    <div class="current-body">
        <span class="q-index"><%= title %></span>
        <span class-"q-text"><%= body %></span>
    </div>
</script>

Rails试图将这些解析为erb变量,并抛出一个ArgumentError错误。在这种情况下,我该如何使下划线模板与Rails协同工作?我做错了什么?

2个回答

52

使用一些其他分隔符代替 <%= %>。例如,要使用胡须样式的括号 {{= }} (插值) 和 {{ }}(求值),在你的 Javascript 中添加以下内容:

_.templateSettings = {
    interpolate: /\{\{\=(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g
};

谢谢,这个可行。我一直在阅读 _.template 的文档,里面提到了 _.templateSettings,但是在设置项目时不知道为什么就忘了它,一直以为这可能与 Jammit 有关。 - paddle42380
3
谢谢。FYI:http://documentcloud.github.com/underscore/#template 和 https://dev59.com/xW025IYBdhLWcg3w1JiG。 - Francois
6
如果您想在模板中使用 if (x) {} 样式块,则使用 {{ }}{{= }} 可能会导致问题。在这种情况下,使用 [% %][%= %] 可能更容易: - Ash Berlin-Taylor
另一个不需要全局替换的选项是指定插值和求值到特定的方法调用_.template($("#q-template").html(),null, { interpolate : /\{\{\=(.+?)\}\}/g, evaluate: /\{\{(.+?)\}\}/g }); - katzmopolitan

27

如果您不想在整个项目中更改模板设置...

转义ERB标签<%=变成<%%=

<script type="text/template" id="q-template">
    <div class="current-body">
        <span class="q-index"><%%= title %></span>
        <span class-"q-text"><%%= body %></span>
    </div>
</script>

请注意,结束标记仍然是%>,而不是%%>


顺便说一下 - 我也尝试过使用 heredoc 输出。以下代码成功运行,但输出了一堆 erb 源代码,这些源代码被 heredoc 命令夹在中间。

<script type="text/template" id="q-template">
<%= <<-heredoc %>
    <div class="current-body">
        <span class="q-index"><%%= title %></span>
        <span class-"q-text"><%%= body %></span>
    </div>
heredoc
</script>

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