Last active
October 29, 2023 11:21
-
-
Save tmarshall/31e640e1fa80c597cc5bf78566b1274c to your computer and use it in GitHub Desktop.
Lazy javascript template literals
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
const templatized = (template, vars = {}) => { | |
const handler = new Function('vars', [ | |
'const tagged = ( ' + Object.keys(vars).join(', ') + ' ) =>', | |
'`' + template + '`', | |
'return tagged(...Object.values(vars))' | |
].join('\n')) | |
return handler(vars) | |
} | |
const templateString1 = 'Hello ${name}!' | |
console.log(templatized(templateString1, { | |
name: 'world' | |
})) | |
// Hello world! | |
const templateString2 = 'Example with ${thing}.' | |
const thing = 'globals' | |
console.log(templatized(templateString2)) | |
// Example with globals. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Many thanks for this, was looking for something to handle runtime creation of template literals (for different email templates, etc)
Normally use an object so have modified it slightly to:
then