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

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


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


You could do it by just putting the result in a temporary container and taking the innerHTML of it, like this:

var str = $("<div />").append($.tmpl(myTemplate, myData)).html();


jQuery.tmpl returns an HTMLElement wrapped in a jQuery object, which could be used in the same way as rendered strings were in the old template system.

var $template = $('#template'),    html = $.tmpl($template, data).get();

I suspect that this might actually be faster than regular strings, but I don't have any profiling data for this yet.


Update

I did some basic profiling between Mustache.js and jQuery.tmpl, and the stats do not look good.

I started with 1,000 preloaded records and generated templates for them several times, averaging the results.

Mustache.js: 1783ms
jQuery.tmpl: 2243ms

I might wait until jQuery.tmpl closes that gap before switching.