6

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.

1
  • 1
    Hmm, I didn't even know jquery had this :) Commented Jan 20, 2011 at 1:27

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

2

Getting back to your question, the problem seems to be that htmlDetail needs to be defined before template itself. (their examples 'suggest' that)

It works here: http://jsfiddle.net/SXvsZ/9/

Comments

1

http://api.jquery.com/template-tag-html/

Note this are the beta version anyways so they are not finalised and most likely might change or even be deprecated so don't rely on that too much as of yet ofcourse but do experiment with it :)

1 Comment

Link is not valid anymore
0

You can pass the a non global function to the template to make it avialbale inside the template, if you choose not to make it global.

$("#testTemplate").tmpl(book, {htmlDetail : htmlDetail} ).appendTo("#bookList");

it can be used like this, {{html}} will render it with no encoding

 <p>Start: {{html $item.htmlDetail() }} :End</p>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.