javascript function inside jquery template

Anthony Webb picture Anthony Webb · Jan 20, 2011 · Viewed 20.2k times · Source

Seems I am having some issues calling a javascript function inside a jquery template. I've got a demo set up here: http://jsfiddle.net/SXvsZ/8/

Code looks like:

function htmlDetail(){
   return "hello <strong>world</strong>"; 
}

var book = [
    { title: "Goodnight, World!",
  detail: { author: "Jojo Mojo", synopsis : "What the ..." }},
{ title: "Rainbow",
  detail: { author: "Cookie", synopsis : "Huh?" }}
];

$("#testTemplate").tmpl(book).appendTo("#bookList");

and the template looks like:

<script id="testTemplate" type="text/x-jquery-tmpl">
    {{if title.length}}
      <h3>${title}</h3>
      <p>Start: ${ htmlDetail() } :End</p>
    {{/if}}
</script>

<div id="bookList"></div>

Seems like it should render "hello world" I'd like to have it also render the HTML as html and not plain text.

Answer

Harborhoffer picture Harborhoffer · Jan 20, 2011

To render html inside the template from another function, you will need to use the {{html}} template tag.

<script id="testTemplate" type="text/x-jquery-tmpl">
    {{if title.length}}
      <h3>${title}</h3>
      <p>Start: {{html htmlDetail() }} :End</p>
    {{/if}}
</script>

You should also move the htmlDetail function outside of your ready() function