首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用doT.js的外部模板?

使用doT.js的外部模板?
EN

Stack Overflow用户
提问于 2014-03-13 23:06:31
回答 2查看 1.5K关注 0票数 1

我使用doT.js来管理视图模板等等,我想加载一个外部模板(将它放在另一个文件夹中,然后像CSS文件或JS文件一样加载它)可以用doT.js实现吗?如果没有,什么模板引擎能让我做到这一点呢?我不喜欢使用jQuery,只使用原生JS。

EN

回答 2

Stack Overflow用户

发布于 2015-03-01 04:08:26

我知道您没有要求查询,但对于其他人来说,这是一种将模板作为字符串返回的简单方法,您可以立即将其传递给doT。请注意,这是同步的。这可能不是你想要的,但这很容易改变:

代码语言:javascript
复制
function getTemplate(templateUrl) {
    return $.ajax({
        type: "GET",
        url: templateUrl,
        async: false
    }).responseText;
}
票数 1
EN

Stack Overflow用户

发布于 2014-03-14 21:52:15

加载这些模板视图的最好方法是使用XHR调用获取它们,然后将它们附加到文档中:

代码语言:javascript
复制
function appendDotTemplate(idName) {
if (window.XMLHttpRequest) {
    var myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) {
    var myRequest = new ActiveXObject("Microsoft.XMLHTTP");
} else {
    console.log("XMLHttpRequest not supported!");
    return;
}

myRequest.onreadystatechange = function () {
    // XMLHttpRequest.onreadystatechange() is personnalized in orded to meet our specific needs.
    if (myRequest.readyState != 4)
        return;
    if (myRequest.status != 200) {
        console.log('Failed to retrive the template! Error : '+myRequest.status);
        // If the request failed, subscribers will be notified with the 'fail' argument.
        return;
    }
    console.log("Debug: Request status = " + _request.status + " .");
    if (myRequest.readyState == 4)
        if (myRequest.status == 200) {
            // It the request succeed :
            // append the new retrived template to the document
            myTemplate = myRequest.responseText;
            var obj = document.createElement("script");
            obj.id = idName; // set an ID to the template in order to manipulate it
            obj.language = "javascript";
            obj.type = 'text/x-dot-template';
            obj.defer = true;
            obj.text = content;
            document.body.appendChild(obj);
            console.log('myTemplate was loaded and append to the document.');
        }
}

希望它能帮助其他人:)。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22382809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档