2011-09-22 69 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>