Skip to content

Instantly share code, notes, and snippets.

@edykim
Last active March 7, 2024 18:58
Show Gist options
  • Select an option

  • Save edykim/c9ab5436d5a7fb3e80b7c75fc729bfc0 to your computer and use it in GitHub Desktop.

Select an option

Save edykim/c9ab5436d5a7fb3e80b7c75fc729bfc0 to your computer and use it in GitHub Desktop.
template function using string literals
"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
@edykim
Copy link
Author

edykim commented Mar 4, 2024

Quick and dirty poc for template function using string literals.

import fs from 'fs'
const content = fs.readFileSync("./some-template.html");
const page = template(content);
// ...
const rendered = page({user: {name: "Guest"}});
console.log(rendered);

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