Skip to content

Instantly share code, notes, and snippets.

@anuraghazra
Last active August 2, 2024 09:48
Show Gist options
  • Save anuraghazra/5d7c1706904b7de18610530f467e935e to your computer and use it in GitHub Desktop.
Save anuraghazra/5d7c1706904b7de18610530f467e935e to your computer and use it in GitHub Desktop.
Minimal Templating Engine In Javascript
// magic!
function dom<Props extends Record<string, unknown>>(
str: TemplateStringsArray,
...args: string[] | ((props: Props) => string)[]
) {
const interleaved = args.flatMap((arg, index) => {
return [arg, str[index + 1]];
});
return (props?: Props) =>
[str[0], ...interleaved]
.map((part) => {
return typeof part === "function" ? part(props!) : part;
})
.join("");
}
const Message = dom`<span>Hello</span>`;
const Greeting = dom<{ color: string; name: string }>`
<p>
${Message}
<span style="color: ${(p) => p.color}">${(p) => p.name}</span>
</p>
`;
// Main component
const Component = dom`
<h3>Ladies and gentlemen: Tagged Template Literals! ✨</h3>
${Greeting({ name: "Anurag Hazra", color: "red" })}
`;
document.body.innerHTML = Component();
@0xkarambit
Copy link

Damn thats great code bro ! took me a while to understand but its brilliant ! 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment