forked from premasagar/tim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tim-lite.js
58 lines (45 loc) · 1.22 KB
/
tim-lite.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
/*!
* 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
*/
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){
return "";
}
// Return the required value
if (i === len - 1){
return lookup;
}
}
});
};
}());