A third option for using jQuery templates

Dave Ward has a great post about defining jQuery templates. There’s a third method that he doesn’t mention in his post. The “embedd-and-grab/clone” method. I’ve used this method before for simple element cloning of templates.

<div id="templates">
    <div id="hello">
        <p>Hello, ${name}.</p>
    </div>
</div>

We can create a div, or really any element you want, to hold our templates. What does this gain us? Well if we are using a design tool, we can see what the template will look like before we have to render it. That may make it easier for a designer on your project. We don’t have to make an AJAX call out to retrieve the external template, although Dave talks about how this really isn’t an issue if you have caching set up correctly on your server. And frankly, for the amount of bytes that are in a typical template I can’t imagine any successful AJAX request taking very long.

To use them, you simply grab the templates div and detach it from the DOM. If you assign the detached elements to a var, you can just use jQuery selectors to find the one you want to use. Because, remember most of the jQuery methods return the jQuery object itself.

var templates = ​$("#templates")​​​​​​​​​.detach();
$.tmpl(templates.find("#hello").text(), person);​​​

Why do you want to use the detach method rather than the remove method? The detach method removes the elements from the DOM but keeps any jQuery data associated with them intact. Meaning you can use the $.data() method to add data to your templates and access the data before you compile your templates.
Dave Ward points out that I need to use “tempates.find()” rather than the default selector method on the jQuery object. Noted and updated