I want to create a jQuery template(s) that will be used project wide. I would prefer to put the templates in a separate file or files and compile them on project start up using the template function.
I don't want to have the templates in the markup, in script tags. Is this possible and how would I do it?
As RoccoC5 suggested it, you can define a small plugin which will fetch your remote template and then append its content into a script tag to the head:
(function ($) {
$.loadTmpl = function (url, name) {
return $.get(url).success(function (content){
$("head").append($('<script/>', {
id: name,
type: 'text/template'
}).html(content));
});
};
}(jQuery));
and use it with:
$.loadTmpl('hi.html', 'hi').done(function () {
$('#hi').tmpl({name: 'Tom'}).appendTo('body');
});
or:
$.when(
$.loadTmpl('foo.html', 'foo'),
$.loadTmpl('bar.html', 'bar'),
...
).done(function () {
// All your templates are now loaded
});
Hope this help.
Templates are just used as strings, so you don't even have to inject scripts. Just pass the string straight to jQuery.template. So tweaking what @abernier suggested, you can do something like following. I make the assumption that you name the files the same name as the template name you want to use and you store them in TMPLPATH.
$.loadTmpl = function (name) {
return $.get(TMPLPATH + name + ".tmpl").success(function (content){
$.template(name, content);
});
};
来源:https://stackoverflow.com/questions/6993590/making-jquery-templates-reusable