我使用doT.js来管理视图模板等等,我想加载一个外部模板(将它放在另一个文件夹中,然后像CSS文件或JS文件一样加载它)可以用doT.js实现吗?如果没有,什么模板引擎能让我做到这一点呢?我不喜欢使用jQuery,只使用原生JS。
发布于 2015-03-01 04:08:26
我知道您没有要求查询,但对于其他人来说,这是一种将模板作为字符串返回的简单方法,您可以立即将其传递给doT。请注意,这是同步的。这可能不是你想要的,但这很容易改变:
function getTemplate(templateUrl) {
return $.ajax({
type: "GET",
url: templateUrl,
async: false
}).responseText;
}发布于 2014-03-14 21:52:15
加载这些模板视图的最好方法是使用XHR调用获取它们,然后将它们附加到文档中:
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.');
}
}希望它能帮助其他人:)。
https://stackoverflow.com/questions/22382809
复制相似问题