UNPKG

@wowter/templater

Version:

templater demo: primitive simple html/css templating with javascript only

76 lines (67 loc) 2.48 kB
// Encoding: UTF-8 // templater/assets/javascript/modules/src/templater.js /** * Simple Modal class, for very simple html templating with only javascript. * * @author Wouter J. van den Brink/ wowter.napnop.net / @wowter <> * @copyright Wouter J. van den Brink 2020 * @license MIT * @see {@link ./LICENSE.md license text} * */ class Templater { constructor () { // console.log(document.getElementsByTagName("body")[0]); let variables = JSON.parse(document.querySelector("[data-variables]").getAttribute("data-variables")); let allIncludes = document.querySelectorAll("[data-include]"); this.handleIncludes(allIncludes, variables); } handleIncludes(includes, variables){ includes.forEach((include)=> { let includePath = include.attributes.getNamedItem("data-include").value; this.fetchInclude(include, includePath, variables); }) } fetchInclude(includeInElement, includePath, variables){ // parameter variables is needed for the eval expression fetch(includePath) .then((response) => { return response.text(); }) .then((myText) => { includeInElement.innerHTML = eval("`" + myText + "`"); // look for data-variables in the template and update variables as needed if(includeInElement.querySelector("[data-variables]")){ let tempObject = JSON.parse(includeInElement.querySelector("[data-variables]").getAttribute("data-variables")); variables = {...variables, ...tempObject};// tempObject overwrites identical element in variables: perhaps the other way around? } // look for script tags and decide what to do if(includeInElement.querySelectorAll("script").length > 0){ includeInElement.querySelectorAll("script").forEach((scriptItem)=>{ console.log(scriptItem); if(scriptItem.hasAttribute("src")){ console.log(scriptItem.getAttribute("src")); // fetch it!! fetch(scriptItem.getAttribute("src")) .then((response) => { return response.text(); }) .then((myText) => { eval(myText); }); }else { console.log(scriptItem.textContent); // eval it!! eval(scriptItem.textContent); }; }); } // look for data-includes in the template let followIncludes = includeInElement.querySelectorAll("[data-include]"); if(followIncludes.length > 0){ this.handleIncludes(followIncludes, variables); } }); } } export { Templater }