【问题标题】:jQuery templates - where should I put them?jQuery 模板 - 我应该把它们放在哪里?
【发布时间】:2011-06-10 19:52:11
【问题描述】:

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

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

我的代码看起来像示例!

【问题讨论】:

  • 我认为模板的目的是让您可以将常见的内容分成单独的文件?您使用的是什么模板引擎,您的代码是什么样的,到目前为止您尝试过什么?
  • @jmort253 更新帖子以回答您的问题。

标签: jquery jquery-templates


【解决方案1】:

查看这个堆栈溢出问题,这里有很多示例编辑:可能已过时 Recommended JavaScript HTML template library for JQuery?

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

【讨论】:

  • 我不会推荐第一个链接,因为问题和答案都是旧的。已经足够老了,不包括 jQuery 本身提供的最新模板插件,效果很好。
【解决方案2】:

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

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

这东西基本上只是去一个路径,复制粘贴所有的html文件,并在上面附加script type="text/x-jquery-tmpl"部分.

如果您需要更加自动化,这里有一些其他代码可以将模板附加到 html/aspx 文件的 body

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

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

希望对你有帮助

【讨论】:

    【解决方案3】:

    我基本同意这个答案的说法: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");
    }
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2016-08-25
      • 2013-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多