Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I render a jQuery.tmpl Template to a String?

The documentation for jquery.tmpl uses .appendTo to insert the template into the DOM during the rendering process:

$.tmpl( myTemplate, myData ).appendTo( "#target" );

I am attempting to convert an existing app from another templating engine, and my code needs to render a template into a string first before it is added to the DOM. Is this possible? How would that be done?

like image 816
Adam Lassek Avatar asked Oct 21 '10 19:10

Adam Lassek


1 Answers

The answers here didn't help me, however Adam's reply set me on the right track: any jQuery wrapped element has a .html() method.

var output = $( "#infoWindowTemplate" ).tmpl( city_data ).html()

or if you need text...

var output = $( "#infoWindowTemplate" ).tmpl( city_data ).text()

but please take note, that the outermost(root) element of the template is skipped, so you should make your templates look something like this:

  <script id='infoWindowTemplate' type='text/x-jquery-tmpl'> 
    <div class='city_info'>
      <h1 class='title'><a href="${link}">${name}</a></h1>
      <p class='meta'>${count} offers</p>
    </div>
  </script> 

or just use the jQuery outerHtml plugin ( http://darlesson.com/jquery/outerhtml/ ) and replace .html() with .outerHTML()

like image 64
galileoMonkey Avatar answered Sep 21 '22 08:09

galileoMonkey