Skip to content

Instantly share code, notes, and snippets.

@getflourish
Last active December 14, 2022 15:49
Show Gist options
  • Save getflourish/9338fc0ee213be2a8a0ed8080cc1f499 to your computer and use it in GitHub Desktop.
Save getflourish/9338fc0ee213be2a8a0ed8080cc1f499 to your computer and use it in GitHub Desktop.
Native Template Expression Parsing
function parseExpressions(data, template) {
function stringify(strings, ...values) {
function isObject(obj) {
return obj !== null && typeof obj === "object";
}
const toDisplayString = (value) =>
value == null
? ""
: isObject(value)
? JSON.stringify(value, null, 2)
: String(value);
let index = 0;
return strings
.map((s) => (s ? s + toDisplayString(values[index++]) : ""))
.join("");
}
if (data !== undefined) {
return new Function(
"data",
"stringify",
"with(data) {return stringify`" + template + "`}"
)(data, stringify);
}
}
let data = {
name: {
first: "John",
last: "Doe"
}
}
let template = "<span>${name.first} ${name.last}</span>"
parseExpressions(data, template); // => <span>John Doe</span>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment