Skip to content

Instantly share code, notes, and snippets.

@ca0v
Last active January 29, 2022 05:04
Show Gist options
  • Save ca0v/f010695321a90dcde304b5054550fffb to your computer and use it in GitHub Desktop.
Save ca0v/f010695321a90dcde304b5054550fffb to your computer and use it in GitHub Desktop.
Template Library Idea
<!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