Skip to content

Instantly share code, notes, and snippets.

@bsturdivan
Created August 13, 2021 23:13
Show Gist options
  • Save bsturdivan/49b7588ce321be66699842e209eefa56 to your computer and use it in GitHub Desktop.
Save bsturdivan/49b7588ce321be66699842e209eefa56 to your computer and use it in GitHub Desktop.
function parseObject(template, data) {
return new Function('obj', `return obj.${template}`)(data)
}
function htmlStringParse(match, data) {
return Function(
'parseObject',
'data',
'template',
`return parseObject(template, data)`
)(parseObject, data, match)
}
export function template(html, data) {
const parser = new DOMParser()
const reg = /(?<=\${)(.*?)(?=\})/g
const lookarounds = /\${(?=(.*?)(?=\}))|(?<=(?<=\${)(.*?))\}/g
const parsedHtml = html.replaceAll(reg, match => {
return htmlStringParse(match, data)
}).replaceAll(lookarounds, '')
return parser.parseFromString(parsedHtml, "text/html")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment