2011-01-19 12 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> 

my 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

これは私が探していたものによく似ています。私はこれを試みました。しかし、確かに、これは完璧に見える –

+0

+1 - 私は変数、素敵な仕事をフェッチするためにそれを使用しました。増分と減分を探しています:D –

2

あなたのobjectToStringがどこにあるのか分かりませんが、参照hereが表示されている場合は、必要なヘルパー関数を.tmpl(メソッド)に追加しています。ここで

<!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関数を呼び出すことができないのですか? –

関連する問題