Templating of web controls is a valuable technique that allows for code reuse. For example, if you have a repeated list of items with common attributes that need to be displayed on a web page, templating is a great solution. Templating can often be accomplished on the server side through controls such as ASP.NET repeaters. However, with the web of today, asynchronous programming is where it’s at. With AJAX data calls, you often get JSON objects back that must be turned into HTML and displayed on a web page.
There are a few ways of doing so – you could have an asynchronous call return an HTML fragment, for instance (done that). You could also embed placeholders in hidden HTML fragments on a page, and use a combination of jQuery’s clone/replace/append methods to push object data into them (done that too). However, there’s an even better technique available now, as a first-class citizen in the jQuery library – the .tmpl templating API.
jQuery templating is a feature that’s currently in beta (though it is distributed with jQuery as of version 1.4.3), and is based upon an existing templating plugin. I’ve had the pleasure of using the jQuery templating API for a bit of time now, and I admit that it is by far the easiest, most robust templating solution I’ve found. There are template controls for repeaters ({{each}}), conditional statements ({{if}} and {{else}}), templated HTML fragments ({{html}}), and wrapping ({{wrap}}). That’s a lot of functionality out of the box!
By far my favorite part of html templating, however, is the <script type=’text/x-jquery-tmpl’></script> tagging that you can wrap around your template fragments. One thing I’ve disliked with templating is that you have to embed potentially malformed HTML into your page – for instance, you might end up having to template id attributes. Malformed html is not the worst thing in the world, especially in hidden fields, but it certainly doesn’t help with search engine rankings and such. Having a way of clearly saying “I’m a template fragment” is a great thing, both for search engines and general maintainability.
If you haven’t gotten a chance to take a look at jQuery templating, now is certainly a great time to do so. It comes for free with jQuery, and it’s a fast, easy, and robust solution for templating needs.
text/x-jquery-tmpl