Created
April 3, 2023 16:09
-
-
Save jmjuanes/b96c4a3756d342d0ff6591d3dd9d2f0e to your computer and use it in GitHub Desktop.
Tiny template 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
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