异步加载下划线模板的最佳方式

Best way to asynchronously load underscore templates

本文关键字:最佳 方式 加载 下划线 异步      更新时间:2023-09-26

我计划使用backbone.js和underscore.js创建网站,我会有很多下划线模板:

<script type="text/template" id="search_template">
<p id="header">
//header content will go here
</p>
<p id="form">
    <label>Search</label>
    <input type="text" id="search_input" />
    <input type="button" id="search_button" value="Search" />
</p>
<p id="dynamic_date">
//dynamic data will be displayed here
</p>
</script>

当然我的模板要复杂得多。

因为我将有很多模板,我不想每次加载页面时加载所有模板。我想找到一个解决方案,在那里我可以加载特定的模板只有当它将被使用。

另一件事是,我的大多数模板将具有相同的结构,只有<p id="form"></p><p id="dynamic_date"></p>的内容将不同。

你能告诉我该怎么做吗?

谢谢,

编辑:我做了一些研究并移植了我的iCanHaz代码以强调它还使用localStorage

这是一个github存储库:https://github.com/Gazler/Underscore-Template-Loader

代码是:

  (function() {
    var templateLoader = {
      templateVersion: "0.0.1",
      templates: {},
      loadRemoteTemplate: function(templateName, filename, callback) {
        if (!this.templates[templateName]) {
          var self = this;
          jQuery.get(filename, function(data) {
            self.addTemplate(templateName, data);
            self.saveLocalTemplates();
            callback(data);
          });
        }
        else {
          callback(this.templates[templateName]);
        }
      },
      addTemplate: function(templateName, data) {
        this.templates[templateName] = data;
      },
      localStorageAvailable: function() {
       try {
          return 'localStorage' in window && window['localStorage'] !== null;
        } catch (e) {
          return false;
        }
      },
      saveLocalTemplates: function() {
        if (this.localStorageAvailable) {
          localStorage.setItem("templates", JSON.stringify(this.templates));
          localStorage.setItem("templateVersion", this.templateVersion);
        }
      },
      loadLocalTemplates: function() {
        if (this.localStorageAvailable) {
          var templateVersion = localStorage.getItem("templateVersion");
          if (templateVersion && templateVersion == this.templateVersion) {
            var templates = localStorage.getItem("templates");
            if (templates) {
              templates = JSON.parse(templates);
              for (var x in templates) {
                if (!this.templates[x]) {
                  this.addTemplate(x, templates[x]);
                }
              }
            }
          }
          else {
            localStorage.removeItem("templates");
            localStorage.removeItem("templateVersion");
          }
        }
      }

    };
    templateLoader.loadLocalTemplates();
    window.templateLoader = templateLoader;
  })();

调用它看起来像这样:

      templateLoader.loadRemoteTemplate("test_template", "templates/test_template.txt", function(data) {
        var compiled = _.template(data);
        $('#content').html(compiled({name : 'world'}));
      });

这是我的原始答案

下面是我为ICanHaz (mustache)编写的一个方法,它出于同样的原因执行这个完全相同的功能。

window.ich.loadRemoteTemplate = function(name, callback) {
  if (!ich.templates[name+"_template"]) {
    jQuery.get("templates/"+name+".mustache", function(data) {
      window.ich.addTemplate(name+"_template", data);
      callback();
    });
  }
  else {
    callback();
  }
}

我这样称呼它:

ich.loadRemoteTemplate(page+'_page', function() {
  $('#'+page+'_page').html(ich[page+'_page_template']({}, true));
});

我真的很喜欢stackoverflow团队用mvc-miniprofiler做模板的方式。看看这些链接:

Includes.js (Github link)

包括。tmpl (Github link)

如果你的浏览器支持本地存储,它们使用本地存储来本地缓存模板。如果没有,他们就每次都装上。这是处理模板的一种非常巧妙的方法。这也允许你将不需要的模板保存在一个单独的文件中,而不会使你的html混乱。

好运。

虽然以上两种答案都有效,但我发现下面的方法更简单。

将用脚本标签包装的模板放入一个文件中(比如"templates.html"),如下所示:

<script type="text/template" id="template-1">
  <%- text %>
</script>
<script type="text/template" id="template-2">
  oh hai!
</script>

然后是下面的javascript代码:

$(document).ready(function() {
  url ='http://some.domain/templates.html'
  templatesLoadedPromise = $.get(url).then(function(data) {
    $('body').append(data)
    console.log("Async loading of templates complete");
  }).fail(function() {
    console.log("ERROR: Could not load base templates");
  });
});

然后让您非常简单地使用您之前定义的id来选择模板。我添加了承诺

$.when(templatesLoadedPromise).then(function() {
  _.template($('#template-1').html(), {'text':'hello world'} )
});

你可以扩展它,如果你想加载多个文件。

作为旁注,我发现初始页面渲染所需的任何核心模板都更好地嵌入到HTML中(我在服务器上使用龙卷风模块),但上述方法对于以后需要的任何模板都非常有效(例如,在我的情况下,我想跨页面使用的注册小部件的模板非常适合此,因为它只会在用户交互时加载,而不是页面的核心)