-
-
Save getflourish/9338fc0ee213be2a8a0ed8080cc1f499 to your computer and use it in GitHub Desktop.
Native Template Expression Parsing
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
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); | |
} | |
} |
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
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