Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save Luisgustavom1/357bd49b1f4bfe736f071c28acb0c764 to your computer and use it in GitHub Desktop.

Select an option

Save Luisgustavom1/357bd49b1f4bfe736f071c28acb0c764 to your computer and use it in GitHub Desktop.
js template engine
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