1

I'm using doT.js in order to manage view templates and so on, I wanted to load an external template (placing it in another folder then loading it like a CSS file or a JS file) is it possible to make this with doT.js? If not, what templating engine will make me able to do that? I prefer not using jQuery, just native JS.

JstnPwll
  • 8,585
  • 2
  • 33
  • 56

2 Answers2

1

I know you didn't ask for Query, but for others, this is a easy way of returning the template as a string which you can immediately pass to doT. Note that this is synchronous. That may not be what you want but that's easily changed:

function getTemplate(templateUrl) {
    return $.ajax({
        type: "GET",
        url: templateUrl,
        async: false
    }).responseText;
}
David Boyd
  • 6,501
  • 3
  • 21
  • 13
0

The best way to load those template views was to get them with an XHR call and then appending them to the document :

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.');
        }
}

Hope it will help others :) .