2012-06-20 3 views
7

인 경우 밑줄 문자와 함께 _.template() 기능을 사용하고 있습니다. underscore.js의 1.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를 얻을. 이 기능이 제거 되었습니까? 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 특별한 당신의 태그를 청소 :

또한 자바 스크립트 코드 내에서 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> 

데모 :

+0

http://jsfiddle.net/ambiguous/UgATZ/는'print' 기능에 대한 단서가 없었다. 매일 새로운 것을 배우십시오! – tkone

+2

@tkone : 항상 문서를 인용하여 모든 것을 배웁니다. :) –

관련 문제