Skip to content

Instantly share code, notes, and snippets.

@jmjuanes
Created April 3, 2023 16:09
Show Gist options
  • Save jmjuanes/b96c4a3756d342d0ff6591d3dd9d2f0e to your computer and use it in GitHub Desktop.
Save jmjuanes/b96c4a3756d342d0ff6591d3dd9d2f0e to your computer and use it in GitHub Desktop.
Tiny template engine
const compile = (str, data, delimiters = /<%|%>/) => {
const expressionRegex = /(^( )?(if|for|else|switch|case|break|{|}|let|const|var))(.*)?/g;
const result = [
"const r = [];",
...str.split(delimiters).map((t, i) => {
return i % 2 === 0 ? `r.push(\`${t}\`);` : (t.match(expressionRegex) ? t : `r.push(${t});`);
}),
`return r.join("");`,
];
return new Function(result.join("")).apply(data);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment