Last active
March 7, 2024 18:58
-
-
Save edykim/c9ab5436d5a7fb3e80b7c75fc729bfc0 to your computer and use it in GitHub Desktop.
template function using string literals
This file contains hidden or 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
| "use strict"; | |
| function template(html) { | |
| return function parse(context) { | |
| const keys = Object.keys(context); | |
| const params = keys.map(k => context[k]); | |
| return new Function( | |
| ...keys, | |
| 'return (`' + html + '`)') | |
| (...params); | |
| } | |
| } | |
| const hello = template("Hello ${name}!"); | |
| const webpage = template("${hello(user)} This is a web page."); | |
| hello({ name: "world" }); // "Hello world!" | |
| webpage({ user: { name: "Guest", email: "guest@example.com" }, hello }); | |
| // "Hello Guest! This is a web page." | |
| webpage({ user: { name: "Guest", email: "guest@example.com" } }); | |
| // ReferenceError: hello is not defined |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Quick and dirty poc for template function using string literals.