Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Created March 29, 2024 06:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/ffeb296b086fa6a16a4a00466e2da5bf to your computer and use it in GitHub Desktop.
Save ryanmorr/ffeb296b086fa6a16a4a00466e2da5bf to your computer and use it in GitHub Desktop.
Make a static template literal string come alive
function templit(tpl, tag) {
let exec;
return (data) => {
if (!exec) {
const vars = Object.getOwnPropertyNames(data).map((key) => `${key} = this['${key}']`);
exec = tag == null
? new Function(`var ${vars.join(',')}; return \`${tpl}\``)
: new Function('__tag', `var ${vars.join(',')}; return __tag\`${tpl}\``);
}
return tag == null ? exec.call(data) : exec.call(data, tag);
};
}
// Usage:
// Create a template and execute it
const addition = templit('${a} + ${b} = ${a + b}');
addition({a: 1, b: 2}); //=> "1 + 2 = 3"
// Use a tagged template function as an optional second argument
const status = templit('status: ${status}', (strings, ...values) => {
return strings.raw.reduce((acc, str) => acc + values.shift().toUpperCase() + str);
});
status({status: 'ONLINE'}); //=> "message: HELLO WORLD"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment