首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在dot.js中使用html文件和部分视图模板

如何在dot.js中使用html文件和部分视图模板
EN

Stack Overflow用户
提问于 2015-09-03 20:01:19
回答 1查看 540关注 0票数 2

我使用doT.js作为模板引擎,我需要使用html文件作为部分视图模板。有任何方法来传递urls而不是html字符串作为模板吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-03 20:08:03

我找不到这方面的任何文档,但是使用XHR请求读取HTML文件并作为模板字符串传递是很容易的:

假设您有一个获取HTML文件内容的方法

代码语言:javascript
复制
function getPartialView (template) {

  // Return a new promise.
  return new Promise(function(resolve, reject) {
    // Do the usual XHR stuff
    var req = new XMLHttpRequest();
    req.open('GET', "/templates/" + template + ".html", true);
    // req.setRequestHeader('Content-Type', 'Application/JSON');

    req.onreadystatechange = function() {

      if (req.readyState != 4 || req.status != 200) return;

      // This is called even on 404 etc
      // so check the status

        resolve(req.responseText);


    };

    // Handle network errors
    req.onerror = function() {
      reject(Error("Network Error"));
    };

    // Make the request
    req.send();
  });
}

然后,您可以在模板生成器中使用它:

代码语言:javascript
复制
  getPartialView('myTemplate').then(function (result) {

    // getting the template
    var pagefn = doT.template(result, settings);
    // appending to view
    // data is the real data you want to render the template for
      document.querySelector('#mayTemplateWrapper').innerHTML = pagefn(data);

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

https://stackoverflow.com/questions/32384463

复制
相关文章

相似问题

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