I have a page where search results are loaded from an XHR response. What are the advantages of using jQuery templates to display search results in this situation, rather than using a more conventional approach with .html() or .load()?
Using templates allow you to keep a lot of escaped markup outside of Javascript code. Most Javascript solutions now use the technique (first documented, as far as I know, by John Resig): you put the template markup inside a script
tag with a type
attribute set to text/html
(or some other content-type unrecognized by the browser text/tmpl
, text/jstmpl
, whatever).
As for the specific choice of jQuery templating, this is a matter of some discussion. For a while it looked like that code was going to become a part of the core jQuery code, but apparently that's off the agenda.
(There are many alternative templating libraries, though -- personally I like Mustache because it's been ported to many languages besides Javascript, which I find useful.)