使用Underscore.js模板的Rails

pap*_*del 22 backbone.js underscore.js

我试图使用underscore.js模板在rails 2.3应用程序中进行模板化,该应用程序没有 jammit作为资产包装器.

这是简单的模板:

<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>
Run Code Online (Sandbox Code Playgroud)

Rails尝试将这些解析为erb变量并抛出ArgumentError.在这种情况下,如何让下划线模板与rails很好地配合?我哪里错了?

kul*_*esa 52

使用其他一些分隔符而不是<%= %>.例如,要使用胡须样式括号 {{= }}(interpolate)和{{ }}(evaluate),请将其添加到您的javascript:

_.templateSettings = {
    interpolate: /\{\{\=(.+?)\}\}/g,
    evaluate: /\{\{(.+?)\}\}/g
};
Run Code Online (Sandbox Code Playgroud)

  • 如果要在模板中使用`if(x){}`样式块,使用`{{}}`和`{{=}}`可能会导致问题.在这种情况下,使用`[%%]`和`[%=%]`可能更容易: (6认同)
  • 非常感谢:http://documentcloud.github.com/underscore/#template和http://stackoverflow.com/questions/5771742/underscore-js-templates-within-jsp (3认同)

col*_*lin 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>
Run Code Online (Sandbox Code Playgroud)

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


旁注 - 我也尝试使用heredoc输出.以下代码成功运行,但输出了一堆在heredoc命令之间捕获的erb源代码.

<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>
Run Code Online (Sandbox Code Playgroud)