Created
August 13, 2021 23:13
-
-
Save bsturdivan/49b7588ce321be66699842e209eefa56 to your computer and use it in GitHub Desktop.
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 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