Created
February 23, 2022 02:02
-
-
Save samkcarlile/94e970a52f7a006fe6e6902ed09da2de to your computer and use it in GitHub Desktop.
templating engine
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 render(template: string, data: any, brackets = ['{{', '}}']) { | |
const output: string[] = []; | |
const [left, right] = | |
brackets.length > 1 ? brackets : [...brackets, ...brackets]; | |
let pos = 0; | |
while (pos < template.length) { | |
const start = template.indexOf(left, pos); | |
if (start < 0) break; | |
const end = template.indexOf(right, pos); | |
if (end < 0) throw new Error(`expected closing bracket: '${right}'`); | |
output.push(template.slice(pos, start)); | |
const code = 'return ' + template.slice(start + left.length, end).trim(); | |
const fn = new Function('', code).bind(data); | |
output.push(fn()); | |
pos = end + right.length; | |
} | |
output.push(template.slice(pos, template.length)); | |
return output.join(''); | |
} | |
render('{{ this.username.toUpperCase() }}', { | |
username: 'samkcarlile', | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment