If you want to keep your templates in external files, you can load the template in like so:
$.get('/js/templates/filename.html', function(template) {
$.tmpl(template, data).appendTo('#whatever');
});
A couple of benefits of this method:
- Organizing your templates into their own files is tidy.
- Your syntax highlighter will be happier, since you're not writing HTML between two
<script>
tags.
If you're using Require.js it has a super handy
text!
prefix that loads any file into a variable as a string. That's what I do. There are probably standalone libraries that accomplish the same thing without using$.get
, but your way works in a pinch, albeit with a little inline async/callback behavior that could get annoying.Side note:
$.tmpl
is deprecated so you may want to consider a different template engine. Might I suggest the one built into Underscore?