Листинг функции
/**
* Основной формат рендеринга шаблонов
* @param hbsPath {String}
* @param templateElement {HTMLElement}
* @param data {Object|undefined}
* @returns {Promise}
*/
function renderTemplate(hbsPath, templateElement, data) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open('get', hbsPath, true);
req.onloadend = () => {
data = data || {};
const template = Handlebars.compile(req.responseText);
const innerHTML = template(data);
templateElement.innerHTML = innerHTML;
const parser = new DOMParser();
const convertedHtml = parser.parseFromString(innerHTML, 'text/xml');
const childElement = convertedHtml.documentElement;
return resolve(childElement);
};
req.onerror = error => {
reject(error);
};
req.send();
});
}
Демонстрация вызова рендера
var someElem = await renderTemplate(
'./PATH_TO_TEMPLATE.hbs',
document.getElementById('SOME-SCRIIPT-TEMPLATE-ID'),
{}
);