JQuery Template - Executing JS code inside a template

I'm trying to learn more about jQuery templates, but can not seem to make any JS calls inside the template.

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

Please note that my objectToString () function is never called, it just displays as a string. I tried to wrap it {{}} on a whim, but no luck. Anyone who can help?

+5
source share
2 answers
Anthony, you can. Your call method must be inside the template tag, for example:
<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>
+8
source

, objectToString, , , .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> 

.

+2

All Articles