Skip to content

Instantly share code, notes, and snippets.

Last active October 15, 2018 18:24
What would you like to do?
Simple JS template engine
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/html" id="tmpl">
<dt>empty default:</dt>
<script type="text/javascript" src="StringTemplate.js"></script>
<script type="text/javascript">
document.write("sample object");
s: "simple value",
d: "default value",
n: {e: {s: {t: {e: {d: "nested value"}}}}},
f: function() { return "function value"; }
document.write("empty object");
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