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