Skip to content

Instantly share code, notes, and snippets.

@wiky
Last active December 17, 2015 04:28
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 wiky/5550306 to your computer and use it in GitHub Desktop.
Save wiky/5550306 to your computer and use it in GitHub Desktop.
a simple javascript templating
(function (exports) {
var settings = {
open: '<%',
close: '%>',
evaluate: '',
interpolate: '='
};
var matcher = new RegExp([
settings.open,
'([^\\w\\s\}\)]*)\\s*(.*?)\\s*',
settings.close
].join(''), 'g');
exports.tmpl = function (str, data) {
var source = '_p+="';
source += str.replace(matcher, function (match, mark, code) {
if (mark === settings.interpolate) {
return '"+(' + code + ')+"';
}
if (mark === settings.evaluate) {
return '";\n' + code + '\n_p+="';
}
});
source += '";';
source = 'var _p="";\nwith(_||{}){\n' + source + '\n}\nreturn _p;';
var render = new Function('_', source)
return data ? render(data) : render;
};
})(this);
// for test
var a = this.tmpl('<span><%=a%></span>', {
a: 1
});
console.log(a); // "<span>1</span>"
var b = this.tmpl(['<%if (typeof href !== "undefined") {%>',
'<a href=\\"<%=href%>\\"><%=text%></a>',
'<%} else {%>',
'<span><%=text%></span>',
'<%}%>'].join(''));
console.log(b({
href: '/a.html',
text: 'aaa'
})); // "<a href=\"/a.html\">aaa</a>"
console.log(b({
text: 'bbb'
})); // "<span>bbb</span>"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment