views:

36

answers:

2

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?

+1  A: 

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();
Nick Craver
A: 

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.

Adam Lassek