Last active
January 29, 2022 05:04
-
-
Save ca0v/f010695321a90dcde304b5054550fffb to your computer and use it in GitHub Desktop.
Template Library Idea
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<style data-template="{opacity}"> | |
body.dark { | |
background-color: var(--dark-color); | |
color: purple; | |
opacity: var(--opacity); | |
--dark-color: black; | |
--opacity: {opacity}; | |
} | |
</style> | |
</head> | |
<body data-template="{theme}" class="{theme}"> | |
<h1 data-template="{time}">Page Created {time}</h1> | |
<p>The current time is <i data-template="{live-time}">{live-time}</i></p> | |
<script> | |
function applyTemplates() { | |
const templateData = { | |
"{theme}": () => (new Date().getHours() < 8 ? "dark" : "light"), | |
"{opacity}": () => (24 + new Date().getHours()) / 50, | |
"{time}": () => new Date().toLocaleTimeString(), | |
"{hour}": () => new Date().getHours(), | |
"{live-time}": (n) => { | |
setInterval( | |
() => (n.innerText = new Date().toLocaleTimeString()), | |
1000 | |
); | |
return new Date().toLocaleTimeString(); | |
}, | |
}; | |
const templateItems = Array.from( | |
document.querySelectorAll("[data-template]") | |
); | |
templateItems.forEach((node) => { | |
const name = node.dataset.template; | |
const templateFn = templateData[name]; | |
if (!templateFn) throw `unknown template: ${name}`; | |
// apply to innertext | |
if (-1 < node.innerText?.indexOf(name)) { | |
const data = templateFn(node); | |
node.innerText = node.innerText.replaceAll(`${name}`, data); | |
} | |
// apply to attributes | |
node | |
.getAttributeNames() | |
.filter((n) => n !== "data-template") | |
.filter((n) => -1 < node.getAttribute(n)?.indexOf(name)) | |
.forEach((a) => { | |
node.setAttribute(a, templateFn(a)); | |
}); | |
}); | |
} | |
applyTemplates(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment