-
Notifications
You must be signed in to change notification settings - Fork 26
/
tinytim.js
72 lines (56 loc) · 1.73 KB
/
tinytim.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
/*!
* Tim (lite)
* github.com/premasagar/tim
*
*//*
A tiny, secure JavaScript micro-templating script.
*//*
by Premasagar Rose
dharmafly.com
license
opensource.org/licenses/mit-license.php
**
creates global object
tim
**
v0.3.0
*/
(function(name, definition, context) {
if (typeof module != 'undefined' && module.exports) {
module.exports = definition();
} else if (typeof context['define'] == 'function' && context['define']['amd']) {
define(definition);
} else {
context[name] = definition();
}
})('tim', function() {
var tim = (function(){
"use strict";
var start = "{{",
end = "}}",
path = "[a-z0-9_$][\\.a-z0-9_]*", // e.g. config.person.name
pattern = new RegExp(start + "\\s*("+ path +")\\s*" + end, "gi"),
undef;
return function(template, data){
// Merge data into the template string
return template.replace(pattern, function(tag, token){
var path = token.split("."),
len = path.length,
lookup = data,
i = 0;
for (; i < len; i++){
lookup = lookup[path[i]];
// Property not found
if (lookup === undef){
throw "tim: '" + path[i] + "' not found in " + tag;
}
// Return the required value
if (i === len - 1){
return lookup;
}
}
});
};
}());
return tim;
}, this);