Last active
August 2, 2024 09:48
-
-
Save anuraghazra/5d7c1706904b7de18610530f467e935e to your computer and use it in GitHub Desktop.
Minimal Templating Engine In Javascript
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
// 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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Damn thats great code bro ! took me a while to understand but its brilliant ! 👍