jQuery Template - Executing JS code inside the template

Anthony Webb picture Anthony Webb · Jan 19, 2011 · Viewed 9.9k times · Source

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?

Answer

Harborhoffer picture Harborhoffer · Jan 19, 2011

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>