2010-09-20 54 views
11

是否可以在jQuery tmpl模板中創建if句子?在jQuery中使用「if」tmpl

<script id="template" type="text/html"> 
    <h1>${someVar}</h1> 
    if (${intro}!="") 
     <small>${intro}</small> 
    endif 
    <p>${restOfVariables}</p> 
</script> 

現在,這隻會寫出如果作爲文本,所以有沒有辦法做這樣的事情?或者我需要創建兩個不同的模板,並在調用模板之前在我的js中進行檢查?

回答

19

these docs,你可以這樣做:

<script id="template" type="text/html"> 
    <h1>${someVar}</h1> 
    {{if intro != ""}} 
     <small>${intro}</small> 
    {{/if}} 
    <p>${restOfVariables}</p> 
</script> 
+0

Aagh你有一個14第二引線!好吧,我會刪除我基本相同的答案... – Domenic 2010-09-20 06:33:57

+1

不錯!但是Resig的'tmpl'文件使用if/else語句崩潰了。然而,在github上找到了解決這個問題的這個分支:http://github.com/jchadwick/jquery-tmpl – peirix 2010-09-20 07:36:38

+0

僅供參考,在{{和if之間不能有空格。 – 2014-05-13 15:32:38