2011-01-19 46 views
5

我想了解更多關於jQuery模板,但似乎無法執行模板內的任何JS調用。jQuery模板 - 執行模板內的JS代碼

<script id="log-item" type="text/x-jquery-tmpl"> 
{{if title.length }} 
    <h3 style="padding-bottom:5px;">${ title }</h3> 
{{/if}} 
objectToString(${ detail }); 
</script> 

注意,我的ObjectToString()函數永遠不會被調用,就呈現出作爲一個字符串。我嘗試用奇思妙想將它包裹在{{}}中,但沒有運氣。有誰可以幫忙?

回答

8

安東尼,你可以。你的通話方式需要在模板標籤內,如下所示:

<script id="log-item" type="text/x-jquery-tmpl"> 
{{if title.length }} 
    <h3 style="padding-bottom:5px;">${ title }</h3> 
{{/if}} 
<p> 
    Detail: ${ objectToString(detail) } 
</p> 
</script> 
+0

這更像我在找的東西。可以發誓我試過了。但是,這看起來很完美 – 2011-01-19 16:49:14

2

我不確定你的objectToString位於哪裏,但是如果你看到參考here,你會發現他們在.tmpl(method)中添加了必要的幫助函數。

下面是一個例子。我試圖使它類似於你有什麼的問題...

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>Test jquery Templates</title> 
    <script type='text/javascript' src='http://code.jquery.com/jquery-1.4.4.min.js'></script> 
    <script type='text/javascript' src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script> 
</head> 
<body> 
    <script id="testTemplate" type="text/x-jquery-tmpl"> 
    {{if title.length}} 
     <h3>${title}</h3> 
     <p>Detail: ${$item.objectToString("detail")}</p> 
    {{/if}} 
    </script> 
    <div id="bookList"></div> 
    <script type='text/javascript'> 
    $(function(){ 
     var book = [ 
     { title: "Goodnight, World!", 
      detail: { author: "Jojo Mojo", synopsis : "What the ..." }}, 
     { title: "Rainbow", 
      detail: { author: "Cookie", synopsis : "Huh?" }} 
     ]; 

     $("#testTemplate").tmpl(book, { 
     objectToString : function(key) { 
      var detail = this.data[key]; 
      return detail.author + " " + detail.synopsis; 
     } 
     }).appendTo("#bookList"); 
    }); 
    </script> 
</body> 
</html> 

你可以看到它here

+0

事實上,這是答案。看起來很瘋狂。爲什麼不能簡單地在模板中調用JavaScript函數? – 2011-01-19 16:15:16