Making jquery tmpl without a lot of extra script tags
I've been reading about the jQuery template plugin http://api.jquery.com/tmpl/ as a means of binding data to markup. All the examples seem to show that you define the template in a script new script tag. I'd actually prefer开发者_开发百科 not to clutter my html <head>
with all those script tags.
Is there a better way to organize this? Maybe with a templates folder full of scripts that get loaded dynamically?
You don't have to do that. You can (for example) keep your templates in a .js file (sort-of like a message catalog):
// this is a file full of templates
var SITE_TEMPLATES = {
ERROR_1: 'This is an error template: the error is ${error.msg}',
WHATEVER: 'I cannot make this stuff up but you get the ${idea}'
};
Pull that in and then you can use the templates via
$('#someplace').append($.tmpl(SITE_TEMPLATES.ERROR_1, { error: { msg: "hello world" }}));
In other words, $.tmpl()
lets you pass in the template body as the first parameter, and it can come from anywhere.
Alternatively, because it's a little messy to write long templates as Javascript string constants, you could pile up a bunch of text <script>
tags in a single static HTML file. You could then AJAX that and drop it in a hidden <div>
or something. That way you can still get the advantage of caching, and it might be easier to maintain the templates.
Of course, along those lines, you could maintain the templates separately as individual files, and glue them together at site build time according to any packaging scheme.
You can store your templates in external files (and than fetch them via Ajax, for example).
Quote from http://api.jquery.com/jQuery.template/
"... for remote templates, you can get a template markup as a string using any AJAX call you want, or you can simply use a static script block pointing to a js file which defines the string. Then you should use jQuery.template to compile the template from the string, and go from there, rendering it using jQuery.tmpl"
精彩评论