Skip to content

Commit 6508022

Browse files
committed
add t.js template engine
1 parent 3ca35c3 commit 6508022

File tree

1 file changed

+103
-0
lines changed
  • app/assets/javascripts

1 file changed

+103
-0
lines changed

app/assets/javascripts/t.js

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
/*
2+
_ _
3+
| | (_)
4+
| |_ _ ___
5+
| __| | / __|
6+
| |_ _| \__ \
7+
\__(_) |___/
8+
_/ |
9+
|__/
10+
11+
t.js
12+
a micro-templating framework in ~400 bytes gzipped
13+
14+
@author Jason Mooberry <[email protected]>
15+
@license MIT
16+
@version 0.1.0
17+
18+
*/
19+
(function() {
20+
21+
var blockregex = /\{\{(([@!]?)(.+?))\}\}(([\s\S]+?)(\{\{:\1\}\}([\s\S]+?))?)\{\{\/\1\}\}/g,
22+
valregex = /\{\{([=%])(.+?)\}\}/g;
23+
24+
function t(template) {
25+
this.t = template;
26+
}
27+
28+
function scrub(val) {
29+
return new Option(val).innerHTML.replace(/"/g,"&quot;");
30+
}
31+
32+
function get_value(vars, key) {
33+
var parts = key.split('.');
34+
while (parts.length) {
35+
if (!(parts[0] in vars)) {
36+
return false;
37+
}
38+
vars = vars[parts.shift()];
39+
}
40+
return vars;
41+
}
42+
43+
function render(fragment, vars) {
44+
return fragment
45+
.replace(blockregex, function(_, __, meta, key, inner, if_true, has_else, if_false) {
46+
47+
var val = get_value(vars,key), temp = "", i;
48+
49+
if (!val) {
50+
51+
// handle if not
52+
if (meta == '!') {
53+
return render(inner, vars);
54+
}
55+
// check for else
56+
if (has_else) {
57+
return render(if_false, vars);
58+
}
59+
60+
return "";
61+
}
62+
63+
// regular if
64+
if (!meta) {
65+
return render(if_true, vars);
66+
}
67+
68+
// process array/obj iteration
69+
if (meta == '@') {
70+
// store any previous vars
71+
// reuse existing vars
72+
_ = vars._key;
73+
__ = vars._val;
74+
for (i in val) {
75+
if (val.hasOwnProperty(i)) {
76+
vars._key = i;
77+
vars._val = val[i];
78+
temp += render(inner, vars);
79+
}
80+
}
81+
vars._key = _;
82+
vars._val = __;
83+
return temp;
84+
}
85+
86+
})
87+
.replace(valregex, function(_, meta, key) {
88+
var val = get_value(vars,key);
89+
90+
if (val || val === 0) {
91+
return meta == '%' ? scrub(val) : val;
92+
}
93+
return "";
94+
});
95+
}
96+
97+
t.prototype.render = function (vars) {
98+
return render(this.t, vars);
99+
};
100+
101+
window.t = t;
102+
103+
})();

0 commit comments

Comments
 (0)