Skip to content

Instantly share code, notes, and snippets.

@tmarshall
Last active October 29, 2023 11:21
Show Gist options
  • Save tmarshall/31e640e1fa80c597cc5bf78566b1274c to your computer and use it in GitHub Desktop.
Save tmarshall/31e640e1fa80c597cc5bf78566b1274c to your computer and use it in GitHub Desktop.
Lazy javascript template literals
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.
@tomcon
Copy link

tomcon commented Jan 25, 2021

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:

const dynamicTemplate = (template, o) => {
  const handler = new Function( 'o', 'const tagged = (o) => `' + template + '`; return tagged(o)' )
  return handler(o)
}

then

const template1 = 'Hello ${o.name}!'
let o = {name: 'world'}
console.log(dynamicTemplate(template1, o ))
// Hello world!

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