forked from premasagar/tim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tim.js
376 lines (305 loc) · 11.4 KB
/
tim.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
/*!
* Tim
* 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
*//*global window */
/*
TODO:
* a way to prevent a delimiter (e.g. ", ") appearing last in a loop template
* Sorted constructor for auto-sorting arrays - used for parsers -> two parsers are added, one for identifying and parsing single-tokens and one for open/close tokens - the parsers then create two new Sorted instance, one for single-token plugins and one for open/close token plugins
*/
var tim = (function createTim(initSettings){
"use strict";
var settings = {
start: "{{",
end : "}}",
path : "[a-z0-9_][\\.a-z0-9_]*" // e.g. config.person.name
},
templates = {},
filters = {},
stopThisFilter, pattern, initialized, undef;
/////
// Update cached regex pattern
function patternCache(){
pattern = new RegExp(settings.start + "\\s*("+ settings.path +")\\s*" + settings.end, "gi");
}
// settingsCache: Get and set settings
/*
Example usage:
settingsCache(); // get settings object
settingsCache({start:"<%", end:"%>", attr:"id"}); // set new settings
*/
function settingsCache(newSettings){
var s;
if (newSettings){
for (s in newSettings){
if (newSettings.hasOwnProperty(s)){
settings[s] = newSettings[s];
}
}
patternCache();
}
return settings;
}
// Apply custom settings
if (initSettings){
settingsCache(initSettings);
}
else {
patternCache();
}
/////
// templatesCache: Get and set the templates cache object
/*
Example usage:
templatesCache("foo"); // get template named "foo"
templatesCache("foo", "bar"); // set template named "foo" to "bar"
templatesCache("foo", false); // delete template named "foo"
templatesCache({foo:"bar", blah:false}); // set multiple templates
templatesCache(false); // delete all templates
*/
function templatesCache(key, value){
var t;
switch (typeof key){
case "string":
if (value === undef){
return templates[key] || "";
}
else if (value === false){
delete templates[key];
}
else {
templates[key] = value;
}
break;
case "object":
for (t in key){
if (key.hasOwnProperty(t)){
templatesCache(t, key[t]);
}
}
break;
case "boolean":
if (!key){
templates = {};
}
break;
}
return templates;
}
function extend(obj1, obj2){
var key;
for (key in obj2){
if (obj2.hasOwnProperty(key)){
obj1[key] = obj2[key];
}
}
return obj1;
}
/////
// FILTERS
function sortByPriority(a, b){
return a[1] - b[1];
}
// Add filter to the stack
function addFilter(filterName, fn, priority){
var fns = filters[filterName];
if (!fns){
fns = filters[filterName] = [];
}
fns.push([fn, priority || 0]);
fns.sort(sortByPriority);
return fn;
}
function applyFilter(filterName, payload){
var fns = filters[filterName],
args, i, len, substituted;
if (fns){
args = [payload];
i = 2;
len = arguments.length;
for (; i < len; i++){
args.push(arguments[i]);
}
i = 0;
len = fns.length;
for (; i < len; i++){
args[0] = payload;
substituted = fns[i][0].apply(null, args);
if (payload !== undef && substituted !== undef){
payload = substituted;
}
if (stopThisFilter){
stopThisFilter = false;
break;
}
}
}
return payload;
}
// Router for adding and applying filters, for Tim API
function filter(filterName, payload){
return (typeof payload === "function" ? addFilter : applyFilter)
.apply(null, arguments);
}
filter.stop = function(){
stopThisFilter = true;
};
/////
// Merge data into template
/*
// simpler alternative, without support for iteration:
template = template.replace(pattern, function(tag, token){
return applyFilter("token", token, data, template);
});
*/
// TODO: all an array to be passed to tim(), so that the template is called for each element in it
function substitute(template, data){
var match, tag, token, substituted, startPos, endPos, templateStart, templateEnd, subTemplate, closeToken, closePos, key, loopData, loop;
while((match = pattern.exec(template)) !== null) {
token = match[1];
substituted = applyFilter("token", token, data, template);
startPos = match.index;
endPos = pattern.lastIndex;
templateStart = template.slice(0, startPos);
templateEnd = template.slice(endPos);
// If the final value is a function call it and use the returned
// value in its place.
if (typeof substituted === "function") {
substituted = substituted.call(data);
}
if (typeof substituted !== "boolean" && typeof substituted !== "object"){
template = templateStart + substituted + templateEnd;
} else {
subTemplate = "";
closeToken = settings.start + "/" + token + settings.end;
closePos = templateEnd.indexOf(closeToken);
if (closePos >= 0){
templateEnd = templateEnd.slice(0, closePos);
if (typeof substituted === "boolean") {
subTemplate = substituted ? templateEnd : '';
} else {
for (key in substituted){
if (substituted.hasOwnProperty(key)){
pattern.lastIndex = 0;
// Allow {{_key}} and {{_content}} in templates
loopData = extend({_key:key, _content:substituted[key]}, substituted[key]);
loopData = applyFilter("loopData", loopData, loop, token);
loop = tim(templateEnd, loopData);
subTemplate += applyFilter("loop", loop, token, loopData);
}
}
subTemplate = applyFilter("loopEnd", subTemplate, token, loopData);
}
template = templateStart + subTemplate + template.slice(endPos + templateEnd.length + closeToken.length);
}
else {
throw "tim: '" + token + "' not closed";
}
}
pattern.lastIndex = 0;
}
return template;
}
// TIM - MAIN FUNCTION
function tim(template, data){
var templateLookup;
// On first run, call init plugins
if (!initialized){
initialized = 1;
applyFilter("init");
}
template = applyFilter("templateBefore", template);
// No template tags found in template
if (template.indexOf(settings.start) < 0){
// Is this a key for a cached template?
templateLookup = templatesCache(template);
if (templateLookup){
template = templateLookup;
}
}
template = applyFilter("template", template);
// Substitute tokens in template
if (template && data !== undef){
template = substitute(template, data);
}
template = applyFilter("templateAfter", template);
return template;
}
// Get and set settings, e.g. tim({attr:"id"});
tim.settings = settingsCache;
// Get and set cached templates
tim.templates = templatesCache;
// Create new Tim function, based on supplied settings, if any
tim.parser = createTim;
// Add new filters and trigger existing ones. Use tim.filter.stop() during processing, if required.
tim.filter = filter;
/////
// dotSyntax default plugin: uses dot syntax to parse a data object for substitutions
addFilter("token", function(token, data, tag){
var path = token.split("."),
len = path.length,
dataLookup = data,
i = 0;
for (; i < len; i++){
dataLookup = dataLookup[path[i]];
// Property not found
if (dataLookup === undef){
throw "tim: '" + path[i] + "' not found" + (i ? " in " + tag : "");
}
// Return the required value
if (i === len - 1){
return dataLookup;
}
}
});
/////
// Dom plugin: finds micro-templates in <script>'s in the DOM
// This block of code can be removed if unneeded - e.g. with server-side JS
// Default: <script type="text/tim" class="foo">{{TEMPLATE}}</script>
if (window && window.document){
tim.dom = function(domSettings){
domSettings = domSettings || {};
var type = domSettings.type || settings.type || "text/tim",
attr = domSettings.attr || settings.attr || "class",
document = window.document,
hasQuery = !!document.querySelectorAll,
elements = hasQuery ?
document.querySelectorAll(
"script[type='" + type + "']"
) :
document.getElementsByTagName("script"),
i = 0,
len = elements.length,
elem, key,
templatesInDom = {};
for (; i < len; i++){
elem = elements[i];
// Cannot access "class" using el.getAttribute()
key = attr === "class" ? elem.className : elem.getAttribute(attr);
if (key && (hasQuery || elem.type === type)){
templatesInDom[key] = elem.innerHTML;
}
}
templatesCache(templatesInDom);
return templatesInDom;
};
addFilter("init", function(){
tim.dom();
});
}
return tim;
}());
/*jslint browser: true, onevar: true, undef: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */