2012-06-20 37 views
7

條件語句我使用underscorejs的_.template()功能與backbonejs在一起。當使用underscore.js V1.3.0,我可以用一個if聲明如下所示:如果Underscore.js

<script type="text/template" id="tpl_listing_list_item"> 
    <% if(<%= address_2 %>){%>, <%= address_2 %><%}%> 
</script> 

問題:更新到V1.3.3後,我得到的錯誤Uncaught SyntaxError: Unexpected token ILLEGAL在JavaScript控制檯。此功能已被刪除?卸下if代碼修正錯誤。如果它被刪除,是否有另一種方式來實現相同的事情?

回答

8

在你if聲明你已經逃進插值模式,所以<%=是非法字符。

這工作時,我在我的瀏覽器1.3.3

<script type="text/template" id="tpl_listing_list_item"> 
    <% if(address_2){ %>, <%= address_2 %> <% } %> 
</script> 

示例使用它:

var t = _.template('{% if(address_2){ %}, {{ address_2 }} {% } %}') 
undefined 
t({'address_2': 'test'}); 
", test " 

(我們使用JSP所以我們的模板標籤是{% %}{{ }}{%- %}代替默認值,所以原諒我的標籤)

8

tkone具有正確的,但對於一個模板像你這樣,你可以使用特殊的print function來清理你的標籤:

你也可以在JavaScript代碼中使用print。這有時比使用<%= ... %>更方便。

var compiled = _.template("<% print('Hello ' + epithet); %>"); 
compiled({epithet: "stooge"}); 
=> "Hello stooge." 

所以,你可以削減這樣的噪音:

<script type="text/template" id="tpl_listing_list_item"> 
    <% if(address_2){ print(', ', address_2) } %> 
</script> 

演示:http://jsfiddle.net/ambiguous/UgATZ/

+0

還沒有收到有關的'print'功能的線索。每天學些新東西! – tkone

+2

@tkone:你學習各種各樣的事情在回答所有的時間引用文檔:) –