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

kah*_*aha 10 javascript backbone.js underscore.js

我打算使用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>
Run Code Online (Sandbox Code Playgroud)

当然,我的模板会复杂得多.

由于我将拥有大量的内容,因此我不希望每次加载页面时都加载所有模板.我想找到一个解决方案,我只能在使用它时加载特定模板.

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

你能告诉我怎么办?

谢谢,

Gaz*_*ler 8

编辑:我做了一些研究并移植了我的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;
  })();
Run Code Online (Sandbox Code Playgroud)

调用它看起来像:

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

这是我原来的答案

这是我为ICanHaz(胡子)编写的一个方法,它出于同样的原因执行这个功能.

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

然后我这样称呼它:

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