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

标签 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>

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

因为我会有很多模板,所以我不想每次加载页面时都加载所有模板。我想找到一个解决方案,只有在使用特定模板时才能加载它。

另一件事是我的大部分模板都具有相同的结构,只有 <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));
});

关于javascript - 异步加载下划线模板的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7542089/

相关文章:

javascript - 如何在更改下拉列表时显示文本框

javascript - 将平面对象数组转换为嵌套对象

backscore.js 和 underscore.js CDN 推荐吗?

javascript - 如何使用 lodash.js 或 underscore.js 过滤 json?

javascript - 使用不带下划线的 map 重新格式化对象

javascript - "Cannot connect to the Metro server"在 React-Native/Expo 项目上

javascript - Backbone : Adding a model to a collection from a collection view?

javascript - 使用 $(function 等启动 javascript 代码

javascript - 将下划线 sortBy 转换为 javascript

javascript - 添加滑动功能以增加项目