jQuery Template - Executing JS code inside the template

戏子无情 提交于 2019-12-07 04:06:34

问题


I am trying to learn more about jQuery templates but cant seem to execute 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>

Note that my objectToString() function is never called, just rendered out as a string. I tried wrapping it in {{ }} on a whim but no luck. Anyone out there who can help?


回答1:


Anthony, you can. The method your calling needs to be inside a template tag like so:

<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>



回答2:


I am not sure where you have your objectToString is located, but if you see the reference here, you see them adding the necessary helper function into the .tmpl( method).

Here is an example... I tried to make it similar to what you have in the question...

<!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> 

You can see it here.



来源:https://stackoverflow.com/questions/4732853/jquery-template-executing-js-code-inside-the-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!