jQuery模板 - 我应该把它们放在哪里?

LDK*_*LDK 5 jquery jquery-templates

目前我有一个单独的html页面,里面有4个模板,还有更多.是否可以将模板放在不同的文件中并"导入"它们?我可以在.js文件中定义它们吗?

我正在使用jQquery模板插件:http://api.jquery.com/category/plugins/templates/

我的代码看起来像示例!

jus*_*tis 5

我大多同意这个答案:在哪里保留html模板? 由于KISS原则,你已经做了正确的事情.

根据您最终会使用多少个模板(您提到"更多"),您可能希望将它们与主页分开.这有几个原因.

一个原因再次是KISS原则.太多的模板可能会使您的源代码难以导航.您的编辑或IDE可能已经涵盖了这一点.如果没有,这可能是将模板放入单独文件的一个很好的理由.

另一个原因是表现.如果您自己提供HTML文件而没有模板,那么您的页面将到达客户端并开始更快地呈现.您还可以允许客户端缓存某些模板,并在更改时仅加载新模板.这将使您对网站的未来访问更快地初始化.

如果性能特别重要,您可以考虑两种方法的混合.您将在主HTML页面中包含基本模板,即组合页面基本结构的模板.然后,可以在页面加载之后和/或在需要之前获取可选模板.要包含基本模板,您可以使用服务器端模板.

关于你原来的问题,关于在哪里存储它们,我说你应该把它们放在任何有意义的地方.然后,请参阅Dave Ward关于使用外部模板和jQuery模板的文章,了解如何构建和获取模板.这是代码的基本代码:

// 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');
});
Run Code Online (Sandbox Code Playgroud)

然后,请参阅Stephen Walther撰写的"jQuery模板简介",并跳转到标题为"远程模板"的部分.他有一个例子,它只提取和编译模板一次,但可以多次渲染.以下是必不可少的片段:

// 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");
}
Run Code Online (Sandbox Code Playgroud)