Simple JS template engine
This file contains 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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>TestPage</title> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
</head> | |
<body> | |
<script type="text/html" id="tmpl"> | |
<dl> | |
<dt>simple:</dt> | |
<dd>{s}</dd> | |
<dt>default:</dt> | |
<dd>{d|default}</dd> | |
<dt>empty default:</dt> | |
<dd>{ed|}</dd> | |
<dt>nested:</dt> | |
<dd>{n.e.s.t.e.d}</dd> | |
<dt>function:</dt> | |
<dd>{f}</dd> | |
</dl> | |
</script> | |
<script type="text/javascript" src="StringTemplate.js"></script> | |
<script type="text/javascript"> | |
document.write("sample object"); | |
document.write(document.getElementById('tmpl').innerHTML.template({ | |
s: "simple value", | |
d: "default value", | |
n: {e: {s: {t: {e: {d: "nested value"}}}}}, | |
f: function() { return "function value"; } | |
})); | |
document.write("<hr>"); | |
document.write("empty object"); | |
document.write(document.getElementById('tmpl').innerHTML.template({})); | |
</script> | |
</body> | |
</html> |
This file contains 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
String.prototype.template = function (d) { | |
return this.replace(/\{([^\}]+)\}/g, function (m, n) { | |
var o = d, p = n.split('|')[0].split('.'); | |
for (var i = 0; i < p.length; i++) { | |
o = typeof o[p[i]] === "function" ? o[p[i]]() : o[p[i]]; | |
if (typeof o === "undefined" || o === null) return n.indexOf('|') !== -1 ? n.split('|')[1] : m; | |
} | |
return o; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment