Skip to content

Instantly share code, notes, and snippets.

@shawndumas
Last active August 19, 2019 23:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shawndumas/fe1cba368409df8875e9 to your computer and use it in GitHub Desktop.
Save shawndumas/fe1cba368409df8875e9 to your computer and use it in GitHub Desktop.
var template = function (str, options) {
var re = /{{(.+?)}}/g,
reExp = /(^( )?(var|if|for|else|switch|case|break|{|}|;))(.*)?/g,
code = 'with(obj) { var r=[];\n',
cursor = 0,
result,
add = function (line, js) {
js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') :
(code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
return add;
};
while (match = re.exec(str)) {
add(str.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(str.substr(cursor, str.length - cursor));
code = (code + 'return r.join(""); }').replace(/[\r\t\n]/g, '');
try {
result = new Function('obj', code).apply(options, [options]);
}
catch (err) {
console.error("'" + err.message + "'", " in \n\nCode:\n", code, "\n");
}
return result;
};
template('<span id="{{key}}">{{value}}</span>', {key:'monkey_id',value:'monkey'});
//"<span id="monkey_id">monkey</span>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment