forked from BorisMoore/jsrender
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsrender.js
1468 lines (1320 loc) · 52.2 KB
/
jsrender.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
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! JsRender v1.0pre: http://github.com/BorisMoore/jsrender */
/*
* Optimized version of jQuery Templates, for rendering to string.
* Does not require jQuery, or HTML DOM
* Integrates with JsViews (http://github.com/BorisMoore/jsviews)
* Copyright 2013, Boris Moore
* Released under the MIT License.
*/
// informal pre beta commit counter: 34 (Beta Candidate)
(function(global, jQuery, undefined) {
// global is the this object, which is window when running in the usual browser environment.
"use strict";
if (jQuery && jQuery.views || global.jsviews) { return; } // JsRender is already loaded
//========================== Top-level vars ==========================
var versionNumber = "v1.0pre",
$, jsvStoreName, rTag, rTmplString,
//TODO tmplFnsCache = {},
delimOpenChar0 = "{", delimOpenChar1 = "{", delimCloseChar0 = "}", delimCloseChar1 = "}", linkChar = "^",
rPath = /^(?:null|true|false|\d[\d.]*|([\w$]+|\.|~([\w$]+)|#(view|([\w$]+))?)([\w$.^]*?)(?:[.[^]([\w$]+)\]?)?)$/g,
// object helper view viewProperty pathTokens leafToken
rParams = /(\()(?=\s*\()|(?:([([])\s*)?(?:([#~]?[\w$.^]+)?\s*((\+\+|--)|\+|-|&&|\|\||===|!==|==|!=|<=|>=|[<>%*!:?\/]|(=))\s*|([#~]?[\w$.^]+)([([])?)|(,\s*)|(\(?)\\?(?:(')|("))|(?:\s*((\))(?=\s*\.|\s*\^)|\)|\])([([]?))|(\s+)/g,
// lftPrn lftPrn2 path operator err eq path2 prn comma lftPrn2 apos quot rtPrn rtPrnDot prn2 space
// (left paren? followed by (path? followed by operator) or (path followed by left paren?)) or comma or apos or quot or right paren or space
rNewLine = /\s*\n/g,
rUnescapeQuotes = /\\(['"])/g,
// escape quotes and \ character
rEscapeQuotes = /([\\'"])/g,
rBuildHash = /\x08(~)?([^\x08]+)\x08/g,
rTestElseIf = /^if\s/,
rFirstElem = /<(\w+)[>\s]/,
rPrevElem = /<(\w+)[^>\/]*>[^>]*$/,
rAttrEncode = /[><"'&]/g, // Includes > encoding since rConvertMarkers in JsViews does not skip > characters in attribute strings
rHtmlEncode = /[><"'&]/g,
autoTmplName = 0,
viewId = 0,
charEntities = {
"&": "&",
"<": "<",
">": ">",
"\x00": "�",
"'": "'",
'"': """
},
tmplAttr = "data-jsv-tmpl",
slice = [].slice,
$render = {},
jsvStores = {
template: {
compile: compileTmpl
},
tag: {
compile: compileTag
},
helper: {},
converter: {}
},
// jsviews object ($.views if jQuery is loaded)
$views = {
jsviews: versionNumber,
render: $render,
settings: {
delimiters: $viewsDelimiters,
debugMode: true,
tryCatch: true
},
sub: {
// subscription, e.g. JsViews integration
View: View,
Error: JsViewsError,
tmplFn: tmplFn,
parse: parseParams,
extend: $extend,
error: error,
syntaxError: syntaxError
//TODO invoke: $invoke
},
_cnvt: convertVal,
_tag: renderTag,
// TODO provide better debug experience - e.g. support $.views.onError callback
_err: function(e) {
// Place a breakpoint here to intercept template rendering errors
return $viewsSettings.debugMode ? ("Error: " + (e.message || e)) + ". " : '';
}
};
function JsViewsError(message, object) {
// Error exception type for JsViews/JsRender
// Override of $.views.sub.Error is possible
if (object && object.onError) {
if (object.onError(message) === false) {
return;
}
}
this.name = "JsRender Error";
this.message = message || "JsRender error";
}
function $extend(target, source) {
var name;
target = target || {};
for (name in source) {
target[name] = source[name];
}
return target;
}
//TODO function $invoke() {
// try {
// return arguments[1].apply(arguments[0], arguments[2]);
// }
// catch(e) {
// throw new $views.sub.Error(e, arguments[0]);
// }
// }
(JsViewsError.prototype = new Error()).constructor = JsViewsError;
//========================== Top-level functions ==========================
//===================
// jsviews.delimiters
//===================
function $viewsDelimiters(openChars, closeChars, link) {
// Set the tag opening and closing delimiters and 'link' character. Default is "{{", "}}" and "^"
// openChars, closeChars: opening and closing strings, each with two characters
if (!$viewsSub.rTag || arguments.length) {
delimOpenChar0 = openChars ? openChars.charAt(0) : delimOpenChar0; // Escape the characters - since they could be regex special characters
delimOpenChar1 = openChars ? openChars.charAt(1) : delimOpenChar1;
delimCloseChar0 = closeChars ? closeChars.charAt(0) : delimCloseChar0;
delimCloseChar1 = closeChars ? closeChars.charAt(1) : delimCloseChar1;
linkChar = link || linkChar;
openChars = "\\" + delimOpenChar0 + "(\\" + linkChar + ")?\\" + delimOpenChar1; // Default is "{^{"
closeChars = "\\" + delimCloseChar0 + "\\" + delimCloseChar1; // Default is "}}"
// Build regex with new delimiters
// tag (followed by / space or }) or cvtr+colon or html or code
rTag = "(?:(?:(\\w+(?=[\\/\\s\\" + delimCloseChar0 + "]))|(?:(\\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\\*)))"
+ "\\s*((?:[^\\" + delimCloseChar0 + "]|\\" + delimCloseChar0 + "(?!\\" + delimCloseChar1 + "))*?)";
// make rTag available to JsViews (or other components) for parsing binding expressions
$viewsSub.rTag = rTag + ")";
rTag = new RegExp(openChars + rTag + "(\\/)?|(?:\\/(\\w+)))" + closeChars, "g");
// Default: bind tag converter colon html comment code params slash closeBlock
// /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
rTmplString = new RegExp("<.*>|([^\\\\]|^)[{}]|" + openChars + ".*" + closeChars);
// rTmplString looks for html tags or { or } char not preceded by \\, or JsRender tags {{xxx}}. Each of these strings are considered
// NOT to be jQuery selectors
}
return [delimOpenChar0, delimOpenChar1, delimCloseChar0, delimCloseChar1, linkChar];
}
//=========
// View.get
//=========
function getView(inner, type) { //view.get(inner, type)
if (!type) {
// view.get(type)
type = inner;
inner = undefined;
}
var views, i, l, found,
view = this,
root = !type || type === "root";
// If type is undefined, returns root view (view under top view).
if (inner) {
// Go through views - this one, and all nested ones, depth-first - and return first one with given type.
found = view.type === type ? view : undefined;
if (!found) {
views = view.views;
if (view._.useKey) {
for (i in views) {
if (found = views[i].get(inner, type)) {
break;
}
}
} else for (i = 0, l = views.length; !found && i < l; i++) {
found = views[i].get(inner, type);
}
}
} else if (root) {
// Find root view. (view whose parent is top view)
while (view.parent.parent) {
found = view = view.parent;
}
} else while (view && !found) {
// Go through views - this one, and all parent ones - and return first one with given type.
found = view.type === type ? view : undefined;
view = view.parent;
}
return found;
}
function getIndex() {
var view = this.get("item");
return view ? view.index : undefined;
}
getIndex.depends = function() {
return [this.get("item"), "index"];
};
//==========
// View.hlp
//==========
function getHelper(helper) {
// Helper method called as view.hlp(key) from compiled template, for helper functions or template parameters ~foo
var wrapped,
view = this,
res = (view.ctx || {})[helper];
res = res === undefined ? view.getRsc("helpers", helper) : res;
if (res) {
if (typeof res === "function") {
wrapped = function() {
// If it is of type function, we will wrap it so it gets called with view as 'this' context.
// If the helper ~foo() was in a data-link expression, the view will have a 'temporary' linkCtx property too.
// However note that helper functions on deeper paths will not have access to view and tagCtx.
// For example, ~util.foo() will have the ~util object as 'this' pointer
return res.apply(view, arguments);
};
$extend(wrapped, res);
}
}
return wrapped || res;
}
//==============
// jsviews._cnvt
//==============
function convertVal(converter, view, tagCtx) {
// self is template object or linkCtx object
var tmplConverter, tag, value,
boundTagCtx = +tagCtx === tagCtx && tagCtx, // if value is an integer, then it is the key for the boundTagCtx
linkCtx = view.linkCtx;
if (boundTagCtx) {
// Call compiled function which returns the tagCtxs for current data
tagCtx = (boundTagCtx = view.tmpl.bnds[boundTagCtx-1])(view.data, view, $views);
}
value = tagCtx.args[0];
if (converter || boundTagCtx) {
tag = linkCtx && linkCtx.tag || {
_: {
inline: !linkCtx
},
tagName: converter + ":",
flow: true,
_is: "tag"
};
tag._.bnd = boundTagCtx;
if (linkCtx) {
linkCtx.tag = tag;
tag.linkCtx = linkCtx;
tagCtx.ctx = extendCtx(tagCtx.ctx, linkCtx.view.ctx);
}
tag.tagCtx = tagCtx;
tagCtx.view = view;
tag.ctx = tagCtx.ctx || {};
delete tagCtx.ctx;
// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
view._.tag = tag;
converter = converter !== "true" && converter; // If there is a convertBack but no convert, converter will be "true"
if (converter && ((tmplConverter = view.getRsc("converters", converter)) || error("Unknown converter: {{"+ converter + ":"))) {
// A call to {{cnvt: ... }} or {^{cnvt: ... }} or data-link="{cnvt: ... }"
tag.depends = tmplConverter.depends;
value = tmplConverter.apply(tag, tagCtx.args);
}
// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
value = boundTagCtx && view._.onRender
? view._.onRender(value, view, boundTagCtx)
: value;
view._.tag = undefined;
}
return value;
}
//=============
// jsviews._tag
//=============
function getResource(resourceType, itemName) {
var res,
view = this,
store = $views[resourceType];
res = store && store[itemName];
while ((res === undefined) && view) {
store = view.tmpl[resourceType];
res = store && store[itemName];
view = view.parent;
}
return res;
}
function renderTag(tagName, parentView, tmpl, tagCtxs) {
// Called from within compiled template function, to render a template tag
// Returns the rendered tag
var render, tag, tags, attr, isElse, parentTag, i, l, itemRet, tagCtx, tagCtxCtx, content, boundTagFn, tagDef,
ret = "",
boundTagKey = +tagCtxs === tagCtxs && tagCtxs, // if tagCtxs is an integer, then it is the boundTagKey
linkCtx = parentView.linkCtx || 0,
ctx = parentView.ctx,
parentTmpl = tmpl || parentView.tmpl,
parentView_ = parentView._;
if (tagName._is === "tag") {
tag = tagName;
tagName = tag.tagName;
}
// Provide tagCtx, linkCtx and ctx access from tag
if (boundTagKey) {
// if tagCtxs is an integer, we are data binding
// Call compiled function which returns the tagCtxs for current data
tagCtxs = (boundTagFn = parentTmpl.bnds[boundTagKey-1])(parentView.data, parentView, $views);
}
l = tagCtxs.length;
tag = tag || linkCtx.tag;
for (i = 0; i < l; i++) {
tagCtx = tagCtxs[i];
// Set the tmpl property to the content of the block tag, unless set as an override property on the tag
content = tagCtx.tmpl;
content = tagCtx.content = content && parentTmpl.tmpls[content - 1];
tmpl = tagCtx.props.tmpl;
if (!i && (!tmpl || !tag)) {
tagDef = parentView.getRsc("tags", tagName) || error("Unknown tag: {{"+ tagName + "}}");
}
tmpl = tmpl || !i && tagDef.template || content;
tmpl = "" + tmpl === tmpl // if a string
? parentView.getRsc("templates", tmpl) || $templates(tmpl)
: tmpl;
$extend( tagCtx, {
tmpl: tmpl,
render: renderContent,
index: i,
view: parentView,
ctx: extendCtx(tagCtx.ctx, ctx) // Extend parentView.ctx
}); // Extend parentView.ctx
if (!tag) {
// This will only be hit for initial tagCtx (not for {{else}}) - if the tag instance does not exist yet
// Instantiate tag if it does not yet exist
if (tagDef.init) {
// If the tag has not already been instantiated, we will create a new instance.
// ~tag will access the tag, even within the rendering of the template content of this tag.
// From child/descendant tags, can access using ~tag.parent, or ~parentTags.tagName
// TODO provide error handling owned by the tag - using tag.onError
// try {
tag = new tagDef.init(tagCtx, linkCtx, ctx);
// }
// catch(e) {
// tagDef.onError(e);
// }
// Set attr on linkCtx to ensure outputting to the correct target attribute.
tag.attr = tag.attr || tagDef.attr || undefined;
// Setting either linkCtx.attr or this.attr in the init() allows per-instance choice of target attrib.
} else {
// This is a simple tag declared as a function. We won't instantiate a specific tag constructor - just a standard instance object.
tag = {
// tag instance object if no init constructor
render: tagDef.render
};
}
tag._ = {
inline: !linkCtx
};
if (linkCtx) {
// Set attr on linkCtx to ensure outputting to the correct target attribute.
linkCtx.attr = tag.attr = linkCtx.attr || tag.attr;
linkCtx.tag = tag;
tag.linkCtx = linkCtx;
}
if (tag._.bnd = boundTagFn || linkCtx) {
// Bound if {^{tag...}} or data-link="{tag...}"
tag._.arrVws = {};
}
tag.tagName = tagName;
tag.parent = parentTag = ctx && ctx.tag,
tag._is = "tag";
// Provide this tag on view, for addBindingMarkers on bound tags to add the tag to view._.bnds, associated with the tag id,
}
parentView_.tag = tag;
tagCtx.tag = tag;
tag.tagCtxs = tagCtxs;
tag.rendering = {}; // Provide object for state during render calls to tag and elses. (Used by {{if}} and {{for}}...)
if (!tag.flow) {
tagCtxCtx = tagCtx.ctx = tagCtx.ctx || {};
// tags hash: tag.ctx.tags, merged with parentView.ctx.tags,
tags = tagCtxCtx.parentTags = ctx && extendCtx(tagCtxCtx.parentTags, ctx.parentTags) || {};
if (parentTag) {
tags[parentTag.tagName] = parentTag;
}
tagCtxCtx.tag = tag;
}
}
for (i = 0; i < l; i++) {
tagCtx = tag.tagCtx = tagCtxs[i];
tag.ctx = tagCtx.ctx;
if (render = tag.render) {
itemRet = render.apply(tag, tagCtx.args);
}
ret += itemRet !== undefined
? itemRet // Return result of render function unless it is undefined, in which case return rendered template
: tagCtx.tmpl
// render template/content on the current data item
? tagCtx.render()
: ""; // No return value from render, and no template/content defined, so return ""
}
delete tag.rendering;
tag.tagCtx = tag.tagCtxs[0];
tag.ctx= tag.tagCtx.ctx;
if (tag._.inline && (attr = tag.attr) && attr !== "html") {
ret = attr === "text"
? $converters.html(ret)
: "";
}
return ret = boundTagKey && parentView._.onRender
// Call onRender (used by JsViews if present, to add binding annotations around rendered content)
? parentView._.onRender(ret, parentView, boundTagKey)
: ret;
}
//=================
// View constructor
//=================
function View(context, type, parentView, data, template, key, contentTmpl, onRender) {
// Constructor for view object in view hierarchy. (Augmented by JsViews if JsViews is loaded)
var views, parentView_, tag,
isArray = type === "array",
self_ = {
key: 0,
useKey: isArray ? 0 : 1,
id: "" + viewId++,
onRender: onRender,
bnds: {}
},
self = {
data: data,
tmpl: template,
content: contentTmpl,
views: isArray ? [] : {},
parent: parentView,
ctx: context,
type: type,
// If the data is an array, this is an 'array view' with a views array for each child 'item view'
// If the data is not an array, this is an 'item view' with a views 'map' object for any child nested views
// ._.useKey is non zero if is not an 'array view' (owning a data array). Uuse this as next key for adding to child views map
get: getView,
getIndex: getIndex,
getRsc: getResource,
hlp: getHelper,
_: self_,
_is: "view"
};
if (parentView) {
views = parentView.views;
parentView_ = parentView._;
if (parentView_.useKey) {
// Parent is an 'item view'. Add this view to its views object
// self._key = is the key in the parent view map
views[self_.key = "_" + parentView_.useKey++] = self;
tag = parentView_.tag;
self_.bnd = isArray && (!tag || !!tag._.bnd && tag); // For array views that are data bound for collection change events, set the
// view._.bnd property to true for top-level link() or data-link="{for}", or to the tag instance for a data- bound tag, e.g. {^{for ...}}
} else {
// Parent is an 'array view'. Add this view to its views array
views.splice(
// self._.key = self.index - the index in the parent view array
self_.key = self.index =
key !== undefined
? key
: views.length,
0, self);
}
// If no context was passed in, use parent context
// If context was passed in, it should have been merged already with parent context
self.ctx = context || parentView.ctx;
}
return self;
}
//=============
// Registration
//=============
function compileChildResources(parentTmpl) {
var storeName, resources, resourceName, settings, compile;
for (storeName in jsvStores) {
settings = jsvStores[storeName];
if ((compile = settings.compile) && (resources = parentTmpl[storeName + "s"])) {
for (resourceName in resources) {
// compile child resource declarations (templates, tags, converters or helpers)
resources[resourceName] = compile(resourceName, resources[resourceName], parentTmpl, storeName, settings);
}
}
}
}
function compileTag(name, item, parentTmpl) {
var init, tmpl;
if (typeof item === "function") {
// Simple tag declared as function. No presenter instantation.
item = {
depends: item.depends,
render: item
};
} else {
// Tag declared as object, used as the prototype for tag instantiation (control/presenter)
if (tmpl = item.template) {
item.template = "" + tmpl === tmpl ? ($templates[tmpl] || $templates(tmpl)) : tmpl;
}
if (item.init !== false) {
init = item.init = item.init || function(tagCtx) {};
init.prototype = item;
(init.prototype = item).constructor = init;
}
}
if (parentTmpl) {
item._parentTmpl = parentTmpl;
}
//TODO item.onError = function(e) {
// var error;
// if (error = this.prototype.onError) {
// error.call(this, e);
// } else {
// throw e;
// }
// }
return item;
}
function compileTmpl(name, tmpl, parentTmpl, storeName, storeSettings, options) {
// tmpl is either a template object, a selector for a template script block, the name of a compiled template, or a template object
//==== nested functions ====
function tmplOrMarkupFromStr(value) {
// If value is of type string - treat as selector, or name of compiled template
// Return the template object, if already compiled, or the markup string
if (("" + value === value) || value.nodeType > 0) {
try {
elem = value.nodeType > 0
? value
: !rTmplString.test(value)
// If value is a string and does not contain HTML or tag content, then test as selector
&& jQuery && jQuery(global.document).find(value)[0];
// If selector is valid and returns at least one element, get first element
// If invalid, jQuery will throw. We will stay with the original string.
} catch (e) {}
if (elem) {
// Generally this is a script element.
// However we allow it to be any element, so you can for example take the content of a div,
// use it as a template, and replace it by the same content rendered against data.
// e.g. for linking the content of a div to a container, and using the initial content as template:
// $.link("#content", model, {tmpl: "#content"});
value = elem.getAttribute(tmplAttr);
name = name || value;
value = $templates[value];
if (!value) {
// Not already compiled and cached, so compile and cache the name
// Create a name for compiled template if none provided
name = name || "_" + autoTmplName++;
elem.setAttribute(tmplAttr, name);
// Use tmpl as options
value = $templates[name] = compileTmpl(name, elem.innerHTML, parentTmpl, storeName, storeSettings, options);
}
}
return value;
}
// If value is not a string, return undefined
}
var tmplOrMarkup, elem;
//==== Compile the template ====
tmpl = tmpl || "";
tmplOrMarkup = tmplOrMarkupFromStr(tmpl);
// If options, then this was already compiled from a (script) element template declaration.
// If not, then if tmpl is a template object, use it for options
options = options || (tmpl.markup ? tmpl : {});
options.tmplName = name;
if (parentTmpl) {
options._parentTmpl = parentTmpl;
}
// If tmpl is not a markup string or a selector string, then it must be a template object
// In that case, get it from the markup property of the object
if (!tmplOrMarkup && tmpl.markup && (tmplOrMarkup = tmplOrMarkupFromStr(tmpl.markup))) {
if (tmplOrMarkup.fn && (tmplOrMarkup.debug !== tmpl.debug || tmplOrMarkup.allowCode !== tmpl.allowCode)) {
// if the string references a compiled template object, but the debug or allowCode props are different, need to recompile
tmplOrMarkup = tmplOrMarkup.markup;
}
}
if (tmplOrMarkup !== undefined) {
if (name && !parentTmpl) {
$render[name] = function() {
return tmpl.render.apply(tmpl, arguments);
};
}
if (tmplOrMarkup.fn || tmpl.fn) {
// tmpl is already compiled, so use it, or if different name is provided, clone it
if (tmplOrMarkup.fn) {
if (name && name !== tmplOrMarkup.tmplName) {
tmpl = extendCtx(options, tmplOrMarkup);
} else {
tmpl = tmplOrMarkup;
}
}
} else {
// tmplOrMarkup is a markup string, not a compiled template
// Create template object
tmpl = TmplObject(tmplOrMarkup, options);
// Compile to AST and then to compiled function
tmplFn(tmplOrMarkup, tmpl);
}
compileChildResources(options);
return tmpl;
}
}
//==== /end of function compile ====
function TmplObject(markup, options) {
// Template object constructor
var htmlTag,
wrapMap = $viewsSettings.wrapMap || {},
tmpl = $extend(
{
markup: markup,
tmpls: [],
links: {}, // Compiled functions for link expressions
tags: {}, // Compiled functions for bound tag expressions
bnds: [],
_is: "template",
render: renderContent
},
options
);
if (!options.htmlTag) {
// Set tmpl.tag to the top-level HTML tag used in the template, if any...
htmlTag = rFirstElem.exec(markup);
tmpl.htmlTag = htmlTag ? htmlTag[1].toLowerCase() : "";
}
htmlTag = wrapMap[tmpl.htmlTag];
if (htmlTag && htmlTag !== wrapMap.div) {
// When using JsViews, we trim templates which are inserted into HTML contexts where text nodes are not rendered (i.e. not 'Phrasing Content').
tmpl.markup = $.trim(tmpl.markup);
tmpl._elCnt = true; // element content model (no rendered text nodes), not phrasing content model
}
return tmpl;
}
function registerStore(storeName, storeSettings) {
function theStore(name, item, parentTmpl) {
// The store is also the function used to add items to the store. e.g. $.templates, or $.views.tags
// For store of name 'thing', Call as:
// $.views.things(items[, parentTmpl]),
// or $.views.things(name, item[, parentTmpl])
var onStore, compile, itemName, thisStore;
if (name && "" + name !== name && !name.nodeType && !name.markup) {
// Call to $.views.things(items[, parentTmpl]),
// Adding items to the store
// If name is a map, then item is parentTmpl. Iterate over map and call store for key.
for (itemName in name) {
theStore(itemName, name[itemName], item);
}
return $views;
}
// Adding a single unnamed item to the store
if (item === undefined) {
item = name;
name = undefined;
}
if (name && "" + name !== name) { // name must be a string
parentTmpl = item;
item = name;
name = undefined;
}
thisStore = parentTmpl ? parentTmpl[storeNames] = parentTmpl[storeNames] || {} : theStore;
compile = storeSettings.compile;
if (onStore = $viewsSub.onBeforeStoreItem) {
// e.g. provide an external compiler or preprocess the item.
compile = onStore(thisStore, name, item, compile) || compile;
}
if (!name) {
item = compile(undefined, item);
} else if (item === null) {
// If item is null, delete this entry
delete thisStore[name];
} else {
thisStore[name] = compile ? (item = compile(name, item, parentTmpl, storeName, storeSettings)) : item;
}
if (item) {
item._is = storeName;
}
if (onStore = $viewsSub.onStoreItem) {
// e.g. JsViews integration
onStore(thisStore, name, item, compile);
}
return item;
}
var storeNames = storeName + "s";
$views[storeNames] = theStore;
jsvStores[storeName] = storeSettings;
}
//==============
// renderContent
//==============
function renderContent(data, context, parentView, key, isLayout, onRender) {
// Render template against data as a tree of subviews (nested rendered template instances), or as a string (top-level template).
// If the data is the parent view, treat as layout template, re-render with the same data context.
var i, l, dataItem, newView, childView, itemResult, swapContent, tagCtx, contentTmpl, tag_, outerOnRender, tmplName, tmpl,
self = this,
allowDataLink = !self.attr || self.attr === "html",
result = "";
if (key === true) {
swapContent = true;
key = 0;
}
if (self.tag) {
// This is a call from renderTag or tagCtx.render()
tagCtx = self;
self = self.tag;
tag_ = self._;
tmplName = self.tagName;
tmpl = tagCtx.tmpl;
context = extendCtx(context, self.ctx);
contentTmpl = tagCtx.content; // The wrapped content - to be added to views, below
if ( tagCtx.props.link === false ) {
// link=false setting on block tag
// We will override inherited value of link by the explicit setting link=false taken from props
// The child views of an unlinked view are also unlinked. So setting child back to true will not have any effect.
context = context || {};
context.link = false;
}
parentView = parentView || tagCtx.view;
data = data === undefined ? parentView : data;
} else {
tmpl = self.jquery && (self[0] || error('Unknown template: "' + self.selector + '"')) // This is a call from $(selector).render
|| self;
}
if (tmpl) {
if (!parentView && data && data._is === "view") {
parentView = data; // When passing in a view to render or link (and not passing in a parent view) use the passed in view as parentView
}
if (parentView) {
contentTmpl = contentTmpl || parentView.content; // The wrapped content - to be added as #content property on views, below
onRender = onRender || parentView._.onRender;
if (data === parentView) {
// Inherit the data from the parent view.
// This may be the contents of an {{if}} block
// Set isLayout = true so we don't iterate the if block if the data is an array.
data = parentView.data;
isLayout = true;
}
context = extendCtx(context, parentView.ctx);
}
if (!parentView || parentView.data === undefined) {
(context = context || {}).root = data; // Provide ~root as shortcut to top-level data.
}
// Set additional context on views created here, (as modified context inherited from the parent, and to be inherited by child views)
// Note: If no jQuery, $extend does not support chained copies - so limit extend() to two parameters
if (!tmpl.fn) {
tmpl = $templates[tmpl] || $templates(tmpl);
}
if (tmpl) {
onRender = (context && context.link) !== false && allowDataLink && onRender;
// If link===false, do not call onRender, so no data-linking marker nodes
outerOnRender = onRender;
if (onRender === true) {
// Used by view.refresh(). Don't create a new wrapper view.
outerOnRender = undefined;
onRender = parentView._.onRender;
}
if ($.isArray(data) && !isLayout) {
// Create a view for the array, whose child views correspond to each data item. (Note: if key and parentView are passed in
// along with parent view, treat as insert -e.g. from view.addViews - so parentView is already the view item for array)
newView = swapContent
? parentView :
(key !== undefined && parentView) || View(context, "array", parentView, data, tmpl, key, contentTmpl, onRender);
for (i = 0, l = data.length; i < l; i++) {
// Create a view for each data item.
dataItem = data[i];
childView = View(context, "item", newView, dataItem, tmpl, (key || 0) + i, contentTmpl, onRender);
itemResult = tmpl.fn(dataItem, childView, $views);
result += newView._.onRender ? newView._.onRender(itemResult, childView) : itemResult;
}
} else {
// Create a view for singleton data object. The type of the view will be the tag name, e.g. "if" or "myTag" except for
// "item", "array" and "data" views. A "data" view is from programatic render(object) against a 'singleton'.
newView = swapContent ? parentView : View(context, tmplName||"data", parentView, data, tmpl, key, contentTmpl, onRender);
if (tag_ && !self.flow) {
newView.tag = self;
}
result += tmpl.fn(data, newView, $views);
}
return outerOnRender ? outerOnRender(result, newView) : result;
}
}
return "";
}
//===========================
// Build and compile template
//===========================
// Generate a reusable function that will serve to render a template against data
// (Compile AST then build template function)
function error(message) {
if ($viewsSettings.debugMode) {
throw new $views.sub.Error(message);
}
}
function syntaxError(message) {
error("Syntax error\n" + message);
}
function tmplFn(markup, tmpl, isLinkExpr, convertBack) {
// Compile markup to AST (abtract syntax tree) then build the template function code from the AST nodes
// Used for compiling templates, and also by JsViews to build functions for data link expressions
//==== nested functions ====
function pushprecedingContent(shift) {
shift -= loc;
if (shift) {
content.push(markup.substr(loc, shift).replace(rNewLine, "\\n"));
}
}
function blockTagCheck(tagName) {
tagName && syntaxError('Unmatched or missing tag: "{{/' + tagName + '}}" in template:\n' + markup);
}
function parseTag(all, bind, tagName, converter, colon, html, comment, codeTag, params, slash, closeBlock, index) {
// bind tag converter colon html comment code params slash closeBlock
// /{(\^)?{(?:(?:(\w+(?=[\/\s}]))|(?:(\w+)?(:)|(>)|!--((?:[^-]|-(?!-))*)--|(\*)))\s*((?:[^}]|}(?!}))*?)(\/)?|(?:\/(\w+)))}}/g
// Build abstract syntax tree (AST): [ tagName, converter, params, content, hash, bindings, contentMarkup ]
if (html) {
colon = ":";
converter = "html";
}
slash = slash || isLinkExpr;
var noError, current0,
pathBindings = bind && [],
code = "",
hash = "",
passedCtx = "",
// Block tag if not self-closing and not {{:}} or {{>}} (special case) and not a data-link expression
block = !slash && !colon && !comment;
//==== nested helper function ====
tagName = tagName || colon;
pushprecedingContent(index);
loc = index + all.length; // location marker - parsed up to here
if (codeTag) {
if (allowCode) {
content.push(["*", "\n" + params.replace(rUnescapeQuotes, "$1") + "\n"]);
}
} else if (tagName) {
if (tagName === "else") {
if (rTestElseIf.test(params)) {
syntaxError('for "{{else if expr}}" use "{{else expr}}"');
}
pathBindings = current[6];
current[7] = markup.substring(current[7], index); // contentMarkup for block tag
current = stack.pop();
content = current[3];
block = true;
}
if (params) {
// remove newlines from the params string, to avoid compiled code errors for unterminated strings
params = params.replace(rNewLine, " ");
code = parseParams(params, pathBindings)
.replace(rBuildHash, function(all, isCtx, keyValue) {
if (isCtx) {
passedCtx += keyValue + ",";
} else {
hash += keyValue + ",";
}
return "";
});
}
hash = hash.slice(0, -1);
code = code.slice(0, -1);
noError = hash && (hash.indexOf("noerror:true") + 1) && hash || "";
newNode = [
tagName,
converter || !!convertBack || "",
code,
block && [],
'params:"' + params + '",props:{' + hash + "}"
+ (passedCtx ? ",ctx:{" + passedCtx.slice(0, -1) + "}" : ""),
noError,
pathBindings || 0
];
content.push(newNode);
if (block) {
stack.push(current);
current = newNode;
current[7] = loc; // Store current location of open tag, to be able to add contentMarkup when we reach closing tag
}
} else if (closeBlock) {
current0 = current[0];
blockTagCheck(closeBlock !== current0 && current0 !== "else" && closeBlock);
current[7] = markup.substring(current[7], index); // contentMarkup for block tag
current = stack.pop();
}
blockTagCheck(!current && closeBlock);
content = current[3];
}
//==== /end of nested functions ====
var newNode,
allowCode = tmpl && tmpl.allowCode,
astTop = [],
loc = 0,
stack = [],
content = astTop,
current = [, , , astTop];
markup = markup.replace(rEscapeQuotes, "\\$1");
//TODO result = tmplFnsCache[markup]; // Only cache if template is not named and markup length < ...,
//and there are no bindings or subtemplates?? Consider standard optimization for data-link="a.b.c"
// if (result) {
// tmpl.fn = result;
// } else {
// result = markup;
blockTagCheck(stack[0] && stack[0][3].pop()[0]);
// Build the AST (abstract syntax tree) under astTop
markup.replace(rTag, parseTag);
pushprecedingContent(markup.length);
if (loc = astTop[astTop.length - 1]) {
blockTagCheck("" + loc !== loc && (+loc[7] === loc[7]) && loc[0]);
}
// result = tmplFnsCache[markup] = buildCode(astTop, tmpl);
// }