Skip to content

Instantly share code, notes, and snippets.

@iiidefix
Last active November 6, 2023 05:22
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 iiidefix/f61ef86d11b9f17eb3a8 to your computer and use it in GitHub Desktop.
Save iiidefix/f61ef86d11b9f17eb3a8 to your computer and use it in GitHub Desktop.
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;
});
};
@errorisme
Copy link

I love this and I don't know it is intentional or not, but the combination of nested and function worked perfectly for prototype i.e toUpperCase

console.log('Worked perfectly for: {text.toUpperCase}.'.template({text: 'this should be in upper case'}));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment