使JQuery模板可重用

我想创建一个将在项目范围内使用的jQuery模板。 我更喜欢将模板放在一个单独的文件或文件中,并使用模板函数在项目启动时编译它们。

我不希望在脚本标记中的标记中包含模板。 这有可能,我该怎么做?

正如RoccoC5所建议的那样,您可以定义一个小插件,它将获取您的远程模板,然后将其内容附加到头部的脚本标记中:

(function ($) { $.loadTmpl = function (url, name) { return $.get(url).success(function (content){ $("head").append($('', { id: name, type: 'text/template' }).html(content)); }); }; }(jQuery)); 

并使用它:

 $.loadTmpl('hi.html', 'hi').done(function () { $('#hi').tmpl({name: 'Tom'}).appendTo('body'); }); 

要么:

 $.when( $.loadTmpl('foo.html', 'foo'), $.loadTmpl('bar.html', 'bar'), ... ).done(function () { // All your templates are now loaded }); 

希望这有帮助。

模板仅用作字符串,因此您甚至不必注入脚本。 只需将字符串直接传递给jQuery.template。 因此,调整@abernier建议的内容,您可以执行类似以下操作。 我假设您将文件命名为与要使用的模板名称相同的名称,并将它们存储在TMPLPATH中。

  $.loadTmpl = function (name) { return $.get(TMPLPATH + name + ".tmpl").success(function (content){ $.template(name, content); }); };