Last active
December 17, 2015 04:28
-
-
Save wiky/5550306 to your computer and use it in GitHub Desktop.
a simple javascript templating
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
(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