我基本同意这个答案的说法:Where to keep html templates?
由于KISS 原则,您已经在做正确的事了。
根据您最终会得到多少模板(您提到“更多”),您可能希望将它们与您的主页分开。这有几个原因。
一个原因还是 KISS 原则。太多的模板会使您的源代码难以导航。您的编辑器或 IDE 可能已经涵盖了这一点。如果没有,这可能是将模板放入单独文件的一个很好的理由。
另一个原因是性能。如果您自己提供 HTML 文件,而不使用模板,您的页面将到达客户端并更快地开始呈现。您还可以允许客户端缓存一些模板,并仅在它们更改时加载新模板。这将使以后对您网站的访问初始化得更快。
如果性能特别重要,您可以考虑混合使用这两种方法。您将在主 HTML 页面中包含基本模板,即组装页面基本结构的模板。然后,可以在页面加载后和/或在需要它们之前获取可选模板。要包含基本模板,您可以使用服务器端模板。
关于你最初的问题,关于将它们存储在哪里,我说你应该把它们放在对你有意义的地方。然后,请参阅 Dave Ward's article on using external templates with jQuery templates 了解有关如何构建和获取模板的信息。这是基本的sn-p代码:
// Asynchronously our PersonTemplate's content.
$.get('PersonTemplate.htm', function(template) {
// Use that stringified template with $.tmpl() and
// inject the rendered result into the body.
$.tmpl(template, person).appendTo('body');
});
然后,请参阅An Introduction to jQuery Templates, by Stephen Walther 并跳转到标题为“远程模板”的部分。他有一个示例,该示例仅获取和编译模板一次,但可以多次渲染。以下是基本的 sn-ps:
// Get the remote template
$.get("ProductTemplate.htm", null, function (productTemplate) {
// Compile and cache the template
$.template("productTemplate", productTemplate);
// Render the products
renderProducts(0);
});
function renderProducts() {
// Get page of products
var pageOfProducts = products.slice(pageIndex * 5, pageIndex * 5 + 5);
// Used cached productTemplate to render products
$.tmpl("productTemplate", pageOfProducts).appendTo("#productContainer");
}