Should I use jQuery Templates?
I have a page where search results are loaded from an XHR response. What are the advantages of using jQuery templates to display search resu开发者_Python百科lts 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.)
The main advantages are:
- Using a template engine makes it easy to separate out what's being displayed from how it's being displayed.
- You can reuse templates, if you need them in different scenarios
The main disadvantage of a javascript templating engine is the overhead of execution, but it's only a problem if your template is big.
Hope this helps. Cheers
精彩评论