2011-09-22 79 views
22

我正尝试在rails 2.3应用程序中使用underscore.js模板进行模板制作,不是有jammit作为资产包装器。Rails with 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试图解析这些为雇员再培训局变量,会引发ArgumentError。在这种情况下,如何使用下划线模板来良好地使用滑轨?我哪里错了?

回答

52

使用一些其他分隔符代替<%= %>。例如,使用小胡子式支架{{= }}(插值)和{{ }}(评估),这个地方添加到您的javascript:

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

谢谢,这个工程。我正在浏览_.template的文档,并且在那里提到了_.templateSettings,但是当我设置项目时,它不知何故跳过了我的想法,并一直认为这可能与jammit有关。 – papdel

+3

谢谢FYI:http://documentcloud.github.com/underscore/#template和http://stackoverflow.com/questions/5771742/underscore-js-templates-within-jsp – Francois

+6

使用'{{}}'和'如果您想在模板中使用if(x){}样式块,{{=}}会导致问题。在这种情况下使用'[%%]'和'[%=%]'可能会更容易: –

25

如果你不想在你的整个项目更改模板设置.. 。

逃离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> 

注意,结束标记是STI ll %>,而不是%%>


附注 - 我也尝试使用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>