开发者

javascript function inside jquery template

开发者 https://www.devze.com 2023-02-05 21:04 出处:网络
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/

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 :开发者_StackOverflow中文版 "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.


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


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/


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


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

精彩评论

暂无评论...
验证码 换一张
取 消