Skip to content

Instantly share code, notes, and snippets.

@iiidefix

iiidefix/StringTemplate.js

Last active Oct 15, 2018
Embed
What would you like to do?
Simple JS template engine
<!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>
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