2

I'm using doT.js as template engine and I need to use html files as partial view templates. is there any way to pass urls instead of html string for templates?

s korhani
  • 356
  • 4
  • 12

1 Answers1

1

I couldn't find any documents on this, but it's easy to use XHR requests for reading HTML files and passing to as template string:
suppose you have a method to get content of HTML file

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();
  });
}

then you can use it in your template generator:

  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);

  });
Reyraa
  • 4,174
  • 2
  • 28
  • 54