Skip to content

Instantly share code, notes, and snippets.

@samkcarlile
Created February 23, 2022 02:02
Show Gist options
  • Save samkcarlile/94e970a52f7a006fe6e6902ed09da2de to your computer and use it in GitHub Desktop.
Save samkcarlile/94e970a52f7a006fe6e6902ed09da2de to your computer and use it in GitHub Desktop.
templating engine
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