Created
March 27, 2026 11:40
-
-
Save Luisgustavom1/357bd49b1f4bfe736f071c28acb0c764 to your computer and use it in GitHub Desktop.
js template engine
This file contains hidden or 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 REGEX_REPLACE_PATTERN = /<%([^%>]+)?%>/g | |
| const REGEX_EXECUTION_KEYWORDS = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g | |
| const TemplateEngine = function(html, options) { | |
| let code = 'var r=[];\n'; | |
| let cursor = 0; | |
| let match; | |
| var add = function(line, js) { | |
| if (js) { | |
| code += line.match(REGEX_EXECUTION_KEYWORDS) ? line + '\n' : 'r.push(' + line + ');\n'; | |
| } else { | |
| code += line !== '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : ''; | |
| } | |
| return add; | |
| } | |
| while(match = REGEX_REPLACE_PATTERN.exec(html)) { | |
| const part = html.slice(cursor, match.index); | |
| add(part)(match[1], true); | |
| cursor = match.index + match[0].length; | |
| } | |
| add(html.substr(cursor, html.length - cursor)) | |
| code += 'return r.join("");'; | |
| return new Function(code).apply(options) | |
| } | |
| var template = | |
| 'My skills:' + | |
| '<%if(this.showSkills) {%>' + | |
| '<%for(var index in this.skills) {%>' + | |
| '<a href="#"><%this.skills[index]%></a>' + | |
| '<%}%>' + | |
| '<%} else {%>' + | |
| '<p>none</p>' + | |
| '<%}%>'; | |
| console.log(TemplateEngine(template, { | |
| skills: ["js", "html", "css"], | |
| showSkills: true | |
| })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment