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

时间:2011-01-18 01:59:31

标签: jquery jquery-templates

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

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

我的代码看起来像示例!

3 个答案:

答案 0 :(得分:5)

我大多同意这个答案的旋转:Where to keep html templates? 由于KISS原则,你已经做了正确的事。

根据您最终会使用的模板数量(您提及“更多”),您可能希望将它们与主页分开。这有几个原因。

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

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

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

关于你原来的问题,关于在哪里存储它们,我说你应该把它们放在任何有意义的地方。然后,请参阅Dave Ward's article on using external templates with jQuery templates,了解有关构建和获取模板的信息。这是代码的基本代码:

// 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并跳转到标题为“远程模板”的部分。他有一个例子,它只提取和编译模板一次,但可以多次渲染。以下是必不可少的片段:

// 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");
}

答案 1 :(得分:2)

查看此Stack Overflow问题,这里有很多例子编辑:可能已过时 Recommended JavaScript HTML template library for JQuery?

此外,这是一篇关于使用外部模板文件的最新文章: http://encosia.com/2010/10/05/using-external-templates-with-jquery-templates/

答案 2 :(得分:0)

如果您不使用.NET,我不知道这是否会有所帮助。但我有同样的问题,我写了一些代码来做到这一点:

http://htmldeploy.codeplex.com/SourceControl/changeset/view/228d0905a46b#src%2fHtmlDeploy%2fJqueryTemplate.cs

这件事基本上只是去一个路径并复制并粘贴所有html文件,并在其上附加 script type =“text / x-jquery-tmpl” 部分

如果您需要更加自动化,可以使用以下代码将模板附加到html / aspx文件的 正文

http://htmldeploy.codeplex.com/SourceControl/changeset/view/228d0905a46b#src%2fHtmlDeploy%2fMasterPage.cs

由于需要大量的HTTP请求,我不喜欢外部模板方法。理想情况下,希望它在页面上下载一次,我可以忘记模板。如果您使用的是Asp.net,可以将其放在MasterPage中:)

希望有所帮助