【问题标题】:_underscore templating - loading templates from external files_underscore 模板 - 从外部文件加载模板
【发布时间】:2013-05-05 15:36:54
【问题描述】:

关于 _underscore 模板实用程序等如何加载模板以进行渲染,我已经看到了一些冗长的答案。我在下面的作品:

$.ajax({
    url: 'template.tmp',
    type: 'get',
    success: function(data) {
        $('html').append(data);
    }
});

代码位于 jquery 加载之后,但在任何使用模板的脚本之前。这可以吗,或者是否有理由加载这样的模板不是一个好主意? templates.tmp 文件中包含模板

<script type="text/template" id="tmpId"></script>

标签。它们似乎很快就被加载到了 DOM 中。我准备因为这个实现而受到批评,但我只想知道为什么。如果调用“错误:”而不是“成功:”,我唯一能想到的可能是一些处理。谢谢。

【问题讨论】:

  • 由于$.ajax() 是异步的,您可能会遇到使用这些模板的代码在模板加载到DOM 之前运行的情况。另外,有什么理由不首先在主 HTML 中包含模板?
  • @robertklep 我想我可以先用 setInterval 检查元素的模板相关函数,以检查它们是否在 DOM 中,所以现在代码开始变长。这是一个非常有效的观点,应该检查一下。至于为什么。我到处读到模块化方法是最佳实践。
  • 好吧,模块化方法是值得推荐的,但是一旦你必须开始使用setInterval 来检查 DOM 中模板的可用性,你应该想知道在这个用例中它是否是正确的方法:)也许呈现模板的代码可以按需加载它们(如果需要重复呈现它们,则将它们存储在某个地方)? (perhaps useful)
  • 也许吧。如果我知道它们很可能会被使用,那么提前异步加载它们并检查它们的存在对用户来说会更容易。
  • 没错,这就是为什么我会选择将它们包含在 HTML 开头:)

标签: javascript templates dom underscore.js


【解决方案1】:

我决定制作自己的基于 OO 的解决方案。这是构造函数:

var TemplateLoader = function(templatePath) {
    this.template = templatePath;
    this.loaded = false;
    this.error = false;
}

这些是方法:

TemplateLoader.prototype.setReady = function (state) {
    this.loaded = state;
}
TemplateLoader.prototype.setError = function (state) {
    this.error = state;
}
TemplateLoader.prototype.isReady = function () {
    return this.loaded;
}
TemplateLoader.prototype.isError = function () {
    return this.error;
}
TemplateLoader.prototype.loadTemplate = function() {
        templateLoader = this;
        $.ajax({
            url: this.template,
            type: 'get',
            success: function(data) {
                $('html').append(data);
                templateLoader.setReady(true);
            },
            error: function() {
                templateLoader.setError(true);
            }
        });
}

这是如何使用它:

templateLoader = new TemplateLoader('template.tmpl');
templateLoader.loadTemplate();

并检查模板是否已加载:

templateLoader.isReady() //true for loaded
templateLoader.isError() //true for error loading template, eg. template doesn't exist

再次,如果任何人都可以通过此代码看到的问题提供任何反馈,我将不胜感激。如何检查附加到 HTML 的 DOM 对象。值得吗?

【讨论】:

    猜你喜欢
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-16
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多