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

Adam Lassek picture Adam Lassek · Oct 21, 2010 · Viewed 18.5k times · Source

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?

Answer

galileoMonkey picture galileoMonkey · Jul 25, 2011

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