-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathjs-template.js
2338 lines (2045 loc) · 70.6 KB
/
js-template.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
/*
* @projectDescription js-template - JavaScript templates
* @author Google (Steffen Meschkat), Todd Fast
* @version 1.0
* @website: https://github.com/toddfast/js-template
* @license: Apache
*/
// Copyright 2006 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
/**
* Author: Steffen Meschkat <[email protected]>
*
* @fileoverview A simple formatter to project JavaScript data into
* HTML templates. The template is edited in place. I.e. in order to
* instantiate a template, clone it from the DOM first, and then
* process the cloned template. This allows for updating of templates:
* If the templates is processed again, changed values are merely
* updated.
*
* NOTE(mesch): IE DOM doesn't have importNode().
*
* NOTE(mesch): The property name "length" must not be used in input
* data, see comment in jstSelect_().
*/
// Create a fake define() function to bootstrap our AMD module in
// case define() is not already present
window.__define = window.define || function fakeDefine(moduleName, dependencies, factory) {
window.GOOGLE = window.GOOGLE || {};
window.GOOGLE.templates=factory.call(factory,jQuery);
}
// Define an AMD module
__define("js-template",["jquery"],function(jQuery) {
// Stub window.console.* methods
(function() {
var method;
var noop = function () {};
var methods = [
'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
'timeStamp', 'trace', 'warn'];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
// Only stub undefined methods.
if (!console[method]) {
console[method] = noop;
}
}
}());
var log = function(msg, msgN) {
window.console.log.apply(arguments);
}
// TAF
var JST_ATTRIBUTE_NAMESPACE="data-jst-";
var JSTFN_DATA=JST_ATTRIBUTE_NAMESPACE+"fn";
////////////////////////////////////////////////////////////////////////////
// utils.js
////////////////////////////////////////////////////////////////////////////
var MAPS_DEBUG = false;
// String literals defined globally and not to be inlined. (IE6 perf)
/** @const */ var STRING_empty = '';
/** @const */ var CSS_display = 'display';
/** @const */ var CSS_position = 'position';
// Constants for possible values of the typeof operator.
var TYPE_boolean = 'boolean';
var TYPE_number = 'number';
var TYPE_object = 'object';
var TYPE_string = 'string';
var TYPE_function = 'function';
var TYPE_undefined = 'undefined';
/**
* Wrapper for the eval() builtin function to evaluate expressions and
* obtain their value. It wraps the expression in parentheses such
* that object literals are really evaluated to objects. Without the
* wrapping, they are evaluated as block, and create syntax
* errors. Also protects against other syntax errors in the eval()ed
* code and returns null if the eval throws an exception.
*
* @param {string} expr
* @return {Object|null}
*/
var jsEval = function(expr) {
try {
// NOTE(mesch): An alternative idiom would be:
//
// eval('(' + expr + ')');
//
// Note that using the square brackets as below, "" evals to undefined.
// The alternative of using parentheses does not work when evaluating
// function literals in IE.
// e.g. eval("(function() {})") returns undefined, and not a function
// object, in IE.
return eval('[' + expr + '][0]');
}
catch (e) {
console.error("Exception during eval of expression:\n",expr,'\n',e);
return null;
}
}
var jsLength = function(obj) {
return obj.length;
}
var assert = function(obj) {}
/**
* Copies all properties from second object to the first. Modifies to.
*
* @param {Object} to The target object.
* @param {Object} from The source object.
*/
var copyProperties = function(to, from) {
for (var p in from) {
to[p] = from[p];
}
}
/**
* @param {Object|null|undefined} value The possible value to use.
* @param {Object} defaultValue The default if the value is not set.
* @return {Object} The value, if it is
* defined and not null; otherwise the default
*/
var getDefaultObject = function(value, defaultValue) {
if (typeof value != TYPE_undefined && value != null) {
return /** @type Object */(value);
} else {
return defaultValue;
}
}
/**
* Detect if an object looks like an Array.
* Note that instanceof Array is not robust; for example an Array
* created in another iframe fails instanceof Array.
* @param {Object|null} value Object to interrogate
* @return {boolean} Is the object an array?
*/
var isArray = function(value) {
// TAF: Added undefined check
return value && value != null &&
typeof value == TYPE_object &&
typeof value.length == TYPE_number;
}
/**
* Finds a slice of an array.
*
* @param {Array} array Array to be sliced.
* @param {number} start The start of the slice.
* @param {number} opt_end The end of the slice (optional).
* @return {Array} array The slice of the array from start to end.
*/
var arraySlice = function(array, start, opt_end) {
// Use
// return Function.prototype.call.apply(Array.prototype.slice, arguments);
// instead of the simpler
// return Array.prototype.slice.call(array, start, opt_end);
// here because of a bug in the FF and IE implementations of
// Array.prototype.slice which causes this function to return an empty list
// if opt_end is not provided.
return Function.prototype.call.apply(Array.prototype.slice, arguments);
}
/**
* Jscompiler wrapper for parseInt() with base 10.
*
* @param {string} s string repersentation of a number.
*
* @return {number} The integer contained in s, converted on base 10.
*/
var parseInt10 = function(s) {
return parseInt(s, 10);
}
/**
* Clears the array by setting the length property to 0. This usually
* works, and if it should turn out not to work everywhere, here would
* be the place to implement the browser specific workaround.
*
* @param {Array} array Array to be cleared.
*/
var arrayClear = function(array) {
array.length = 0;
}
/**
* Prebinds "this" within the given method to an object, but ignores all
* arguments passed to the resulting function.
* I.e. var_args are all the arguments that method is invoked with when
* invoking the bound function.
*
* @param {Object|null} object The object that the method call targets.
* @param {Function} method The target method.
* @return {Function} Method with the target object bound to it and
* curried by the provided arguments.
*/
function bindFully(object, method, var_args) {
var args = arraySlice(arguments, 2);
return function() {
return method.apply(object, args);
}
}
// Based on <http://www.w3.org/TR/2000/ REC-DOM-Level-2-Core-20001113/
// core.html#ID-1950641247>.
var DOM_ELEMENT_NODE = 1;
var DOM_ATTRIBUTE_NODE = 2;
var DOM_TEXT_NODE = 3;
var DOM_CDATA_SECTION_NODE = 4;
var DOM_ENTITY_REFERENCE_NODE = 5;
var DOM_ENTITY_NODE = 6;
var DOM_PROCESSING_INSTRUCTION_NODE = 7;
var DOM_COMMENT_NODE = 8;
var DOM_DOCUMENT_NODE = 9;
var DOM_DOCUMENT_TYPE_NODE = 10;
var DOM_DOCUMENT_FRAGMENT_NODE = 11;
var DOM_NOTATION_NODE = 12;
function domGetElementById(document, id) {
return document.getElementById(id);
}
/**
* Creates a new node in the given document
*
* @param {Document} doc Target document.
* @param {string} name Name of new element (i.e. the tag name)..
* @return {Element} Newly constructed element.
*/
function domCreateElement(doc, name) {
return doc.createElement(name);
}
/**
* Traverses the element nodes in the DOM section underneath the given
* node and invokes the given callback as a method on every element
* node encountered.
*
* @param {Element} node Parent element of the subtree to traverse.
* @param {Function} callback Called on each node in the traversal.
*/
function domTraverseElements(node, callback) {
var traverser = new DomTraverser(callback);
traverser.run(node);
}
/**
* A class to hold state for a dom traversal.
* @param {Function} callback Called on each node in the traversal.
* @constructor
* @class
*/
function DomTraverser(callback) {
this.callback_ = callback;
}
/**
* Processes the dom tree in breadth-first order.
* @param {Element} root The root node of the traversal.
*/
DomTraverser.prototype.run = function(root) {
var me = this;
me.queue_ = [ root ];
while (jsLength(me.queue_)) {
me.process_(me.queue_.shift());
}
}
/**
* Processes a single node.
* @param {Element} node The current node of the traversal.
*/
DomTraverser.prototype.process_ = function(node) {
var me = this;
me.callback_(node);
for (var c = node.firstChild; c; c = c.nextSibling) {
if (c.nodeType == DOM_ELEMENT_NODE) {
me.queue_.push(c);
}
}
}
/**
* Get an attribute from the DOM. Simple redirect, exists to compress code.
*
* @param {Element} node Element to interrogate.
* @param {string} name Name of parameter to extract.
* @return {string|null} Resulting attribute.
*/
function domGetAttribute(node, name) {
// TAF: IE7 has a bizarre problem getting custom attributes from
// <table> elements...
try {
return node.getAttribute(name);
}
catch (e) {
if (node.nodeName==="TABLE") {
return null; // Ignore for IE7
}
else {
// Otherwise this is some other weird error
console.error("Exception getting attribute",name,
"from node",node.nodeName,":\n",e.message);
throw e;
}
}
// NOTE(mesch): Neither in IE nor in Firefox, HTML DOM attributes
// implement namespaces. All items in the attribute collection have
// null localName and namespaceURI attribute values. In IE, we even
// encounter DIV elements that don't implement the method
// getAttributeNS().
}
/**
* Set an attribute in the DOM. Simple redirect to compress code.
*
* @param {Element} node Element to interrogate.
* @param {string} name Name of parameter to set.
* @param {string|number} value Set attribute to this value.
*/
function domSetAttribute(node, name, value) {
node.setAttribute(name, value);
}
/**
* Remove an attribute from the DOM. Simple redirect to compress code.
*
* @param {Element} node Element to interrogate.
* @param {string} name Name of parameter to remove.
*/
function domRemoveAttribute(node, name) {
node.removeAttribute(name);
}
/**
* Clone a node in the DOM.
*
* @param {Node} node Node to clone.
* @return {Node} Cloned node.
*/
function domCloneNode(node) {
// TAF: We need to copy event handlers as well. Dunno why this doesn't
// work though; instead, always have to use jQuery.live()
// return node.cloneNode(true);
return jQuery(node).clone(true)[0];
// NOTE(mesch): we never so far wanted to use cloneNode(false),
// hence the default.
}
/**
* Clone a element in the DOM.
*
* @param {Element} element Element to clone.
* @return {Element} Cloned element.
*/
function domCloneElement(element) {
return /** @type {Element} */(domCloneNode(element));
}
/**
* Returns the document owner of the given element. In particular,
* returns window.document if node is null or the browser does not
* support ownerDocument. If the node is a document itself, returns
* itself.
*
* @param {Node|null|undefined} node The node whose ownerDocument is required.
* @returns {Document} The owner document or window.document if unsupported.
*/
function ownerDocument(node) {
if (!node) {
return document;
} else if (node.nodeType == DOM_DOCUMENT_NODE) {
return /** @type Document */(node);
} else {
return node.ownerDocument || document;
}
}
/**
* Creates a new text node in the given document.
*
* @param {Document} doc Target document.
* @param {string} text Text composing new text node.
* @return {Text} Newly constructed text node.
*/
function domCreateTextNode(doc, text) {
return doc.createTextNode(text);
}
/**
* Appends a new child to the specified (parent) node.
*
* @param {Element} node Parent element.
* @param {Node} child Child node to append.
* @return {Node} Newly appended node.
*/
function domAppendChild(node, child) {
return node.appendChild(child);
}
/**
* Sets display to default.
*
* @param {Element} node The dom element to manipulate.
*/
function displayDefault(node) {
// node.style[CSS_display] = '';
jQuery(node).show();
}
/**
* Sets display to none. Doing this as a function saves a few bytes for
* the 'style.display' property and the 'none' literal.
*
* @param {Element} node The dom element to manipulate.
*/
function displayNone(node) {
// node.style[CSS_display] = 'none';
jQuery(node).hide();
}
/**
* Sets position style attribute to absolute.
*
* @param {Element} node The dom element to manipulate.
*/
function positionAbsolute(node) {
node.style[CSS_position] = 'absolute';
}
/**
* Inserts a new child before a given sibling.
*
* @param {Node} newChild Node to insert.
* @param {Node} oldChild Sibling node.
* @return {Node} Reference to new child.
*/
function domInsertBefore(newChild, oldChild) {
return oldChild.parentNode.insertBefore(newChild, oldChild);
}
/**
* Replaces an old child node with a new child node.
*
* @param {Node} newChild New child to append.
* @param {Node} oldChild Old child to remove.
* @return {Node} Replaced node.
*/
function domReplaceChild(newChild, oldChild) {
return oldChild.parentNode.replaceChild(newChild, oldChild);
}
/**
* Removes a node from the DOM.
*
* @param {Node} node The node to remove.
* @return {Node} The removed node.
*/
function domRemoveNode(node) {
return domRemoveChild(node.parentNode, node);
}
/**
* Remove a child from the specified (parent) node.
*
* @param {Element} node Parent element.
* @param {Node} child Child node to remove.
* @return {Node} Removed node.
*/
function domRemoveChild(node, child) {
return node.removeChild(child);
}
/**
* Trim whitespace from begin and end of string.
*
* @see testStringTrim();
*
* @param {string} str Input string.
* @return {string} Trimmed string.
*/
function stringTrim(str) {
return stringTrimRight(stringTrimLeft(str));
}
/**
* Trim whitespace from beginning of string.
*
* @see testStringTrimLeft();
*
* @param {string} str Input string.
* @return {string} Trimmed string.
*/
function stringTrimLeft(str) {
return str.replace(/^\s+/, "");
}
/**
* Trim whitespace from end of string.
*
* @see testStringTrimRight();
*
* @param {string} str Input string.
* @return {string} Trimmed string.
*/
function stringTrimRight(str) {
return str.replace(/\s+$/, "");
}
////////////////////////////////////////////////////////////////////////////
// jsevalcontext.js
////////////////////////////////////////////////////////////////////////////
/**
* Names of special variables defined by the jstemplate evaluation
* context. These can be used in js expression in jstemplate
* attributes.
*/
var VAR_index = '$index';
var VAR_count = '$length';
var VAR_this = '$this';
var VAR_context = '$context';
var VAR_top = '$top';
/**
* The name of the global variable which holds the value to be returned if
* context evaluation results in an error.
* Use JsEvalContext.setGlobal(GLOB_default, value) to set this.
*/
var GLOB_default = '$default';
/**
* Un-inlined literals, to avoid object creation in IE6. TODO(mesch):
* So far, these are only used here, but we could use them thoughout
* the code and thus move them to constants.js.
*/
var CHAR_colon = ':';
var REGEXP_semicolon = /\s*;\s*/;
// TAF
var CHAR_equals = '=';
var REGEXP_pipe = /\s*\|\s*/;
/**
* See constructor_()
* @param {Object|null} opt_data
* @param {Object} opt_parent
* @constructor
*/
function JsEvalContext(opt_data, opt_parent) {
this.constructor_.apply(this, arguments);
}
/**
* Context for processing a jstemplate. The context contains a context
* object, whose properties can be referred to in jstemplate
* expressions, and it holds the locally defined variables.
*
* @param {Object|null} opt_data The context object. Null if no context.
*
* @param {Object} opt_parent The parent context, from which local
* variables are inherited. Normally the context object of the parent
* context is the object whose property the parent object is. Null for the
* context of the root object.
*/
JsEvalContext.prototype.constructor_ = function(opt_data, opt_parent) {
var me = this;
/**
* The context for variable definitions in which the jstemplate
* expressions are evaluated. Other than for the local context,
* which replaces the parent context, variable definitions of the
* parent are inherited. The special variable $this points to data_.
*
* If this instance is recycled from the cache, then the property is
* already initialized.
*
* @type {Object}
*/
if (!me.vars_) {
me.vars_ = {};
}
if (opt_parent) {
// If there is a parent node, inherit local variables from the
// parent.
copyProperties(me.vars_, opt_parent.vars_);
} else {
// If a root node, inherit global symbols. Since every parent
// chain has a root with no parent, global variables will be
// present in the case above too. This means that globals can be
// overridden by locals, as it should be.
copyProperties(me.vars_, JsEvalContext.globals_);
}
/**
* The current context object is assigned to the special variable
* $this so it is possible to use it in expressions.
* @type Object
*/
me.vars_[VAR_this] = opt_data;
/**
* The entire context structure is exposed as a variable so it can be
* passed to javascript invocations through jseval.
*/
me.vars_[VAR_context] = me;
/**
* The local context of the input data in which the jstemplate
* expressions are evaluated. Notice that this is usually an Object,
* but it can also be a scalar value (and then still the expression
* $this can be used to refer to it). Notice this can even be value,
* undefined or null. Hence, we have to protect jsexec() from using
* undefined or null, yet we want $this to reflect the true value of
* the current context. Thus we assign the original value to $this,
* above, but for the expression context we replace null and
* undefined by the empty string.
*
* @type {Object|null}
*/
me.data_ = getDefaultObject(opt_data, STRING_empty);
if (!opt_parent) {
// If this is a top-level context, create a variable reference to the data
// to allow for accessing top-level properties of the original context
// data from child contexts.
me.vars_[VAR_top] = me.data_;
}
};
/**
* A map of globally defined symbols. Every instance of JsExprContext
* inherits them in its vars_.
* @type Object
*/
JsEvalContext.globals_ = {}
/**
* Sets a global symbol. It will be available like a variable in every
* JsEvalContext instance. This is intended mainly to register
* immutable global objects, such as functions, at load time, and not
* to add global data at runtime. I.e. the same objections as to
* global variables in general apply also here. (Hence the name
* "global", and not "global var".)
* @param {string} name
* @param {Object|null} value
*/
JsEvalContext.setGlobal = function(name, value) {
JsEvalContext.globals_[name] = value;
};
/**
* Set the default value to be returned if context evaluation results in an
* error. (This can occur if a non-existent value was requested).
*/
JsEvalContext.setGlobal(GLOB_default, null);
/**
* A cache to reuse JsEvalContext instances. (IE6 perf)
*
* @type Array.<JsEvalContext>
*/
JsEvalContext.recycledInstances_ = [];
/**
* A factory to create a JsEvalContext instance, possibly reusing
* one from recycledInstances_. (IE6 perf)
*
* @param {Object} opt_data
* @param {JsEvalContext} opt_parent
* @return {JsEvalContext}
*/
JsEvalContext.create = function(opt_data, opt_parent) {
if (jsLength(JsEvalContext.recycledInstances_) > 0) {
var instance = JsEvalContext.recycledInstances_.pop();
JsEvalContext.call(instance, opt_data, opt_parent);
return instance;
} else {
return new JsEvalContext(opt_data, opt_parent);
}
};
/**
* Recycle a used JsEvalContext instance, so we can avoid creating one
* the next time we need one. (IE6 perf)
*
* @param {JsEvalContext} instance
*/
JsEvalContext.recycle = function(instance) {
for (var i in instance.vars_) {
// NOTE(mesch): We avoid object creation here. (IE6 perf)
delete instance.vars_[i];
}
instance.data_ = null;
JsEvalContext.recycledInstances_.push(instance);
};
/**
* Executes a function created using jsEvalToFunction() in the context
* of vars, data, and template.
*
* @param {Function} exprFunction A javascript function created from
* a jstemplate attribute value.
*
* @param {Element} template DOM node of the template.
*
* @return {Object|null} The value of the expression from which
* exprFunction was created in the current js expression context and
* the context of template.
*/
JsEvalContext.prototype.jsexec = function(exprFunction, template) {
try {
return exprFunction.call(template, this.vars_, this.data_);
}
catch (e) {
if (!(e instanceof ReferenceError)) { // TAF: quiet for missing props
var functionDeclaration=exprFunction.toString();
try {
functionDeclaration=functionDeclaration.split("{")[0];
}
catch (ex) {
// Ignore
}
console.error("Exception processing template: %o at %o (in %o)",e.message,
template,functionDeclaration);
}
return JsEvalContext.globals_[GLOB_default];
}
};
/**
* Clones the current context for a new context object. The cloned
* context has the data object as its context object and the current
* context as its parent context. It also sets the $index variable to
* the given value. This value usually is the position of the data
* object in a list for which a template is instantiated multiply.
*
* @param {Object} data The new context object.
*
* @param {number} index Position of the new context when multiply
* instantiated. (See implementation of jstSelect().)
*
* @param {number} count The total number of contexts that were multiply
* instantiated. (See implementation of jstSelect().)
*
* @return {JsEvalContext}
*/
JsEvalContext.prototype.clone = function(data, index, count) {
var ret = JsEvalContext.create(data, this);
ret.setVariable(VAR_index, index);
ret.setVariable(VAR_count, count);
return ret;
};
/**
* Binds a local variable to the given value. If set from jstemplate
* jsvalue expressions, variable names must start with $, but in the
* API they only have to be valid javascript identifier.
*
* @param {string} name
*
* @param {Object?} value
*/
JsEvalContext.prototype.setVariable = function(name, value) {
this.vars_[name] = value;
};
/**
* Returns the value bound to the local variable of the given name, or
* undefined if it wasn't set. There is no way to distinguish a
* variable that wasn't set from a variable that was set to
* undefined. Used mostly for testing.
*
* @param {string} name
*
* @return {Object?} value
*/
JsEvalContext.prototype.getVariable = function(name) {
return this.vars_[name];
};
/**
* Evaluates a string expression within the scope of this context
* and returns the result.
*
* @param {string} expr A javascript expression
* @param {Element} opt_template An optional node to serve as "this"
*
* @return {Object?} value
*/
JsEvalContext.prototype.evalExpression = function(expr, opt_template) {
var exprFunction = jsEvalToFunction(expr);
return this.jsexec(exprFunction, opt_template);
};
/**
* Uninlined string literals for jsEvalToFunction() (IE6 perf).
*/
var STRING_a = 'a_';
var STRING_b = 'b_';
var STRING_with = 'with (a_) with (b_) return ';
/**
* Cache for jsEvalToFunction results.
* @type Object
*/
JsEvalContext.evalToFunctionCache_ = {};
/**
* Evaluates the given expression as the body of a function that takes
* vars and data as arguments. Since the resulting function depends
* only on expr, we cache the result so we save some Function
* invocations, and some object creations in IE6.
*
* @param {string} expr A javascript expression.
*
* @return {Function} A function that returns the value of expr in the
* context of vars and data.
*/
var jsEvalToFunction = function(expr) {
if (!JsEvalContext.evalToFunctionCache_[expr]) {
try {
// NOTE(mesch): The Function constructor is faster than eval().
JsEvalContext.evalToFunctionCache_[expr] =
new Function(STRING_a, STRING_b, STRING_with + expr);
} catch (e) {
console.error("Could not eval to expression\n",expr,"\n",e.message);
}
}
return JsEvalContext.evalToFunctionCache_[expr];
}
/**
* Evaluates the given expression to itself. This is meant to pass
* through string attribute values.
*
* @param {string} expr
*
* @return {string}
*/
function jsEvalToSelf(expr) {
return expr;
}
/**
* Parses the value of the jsvalues attribute in jstemplates: splits
* it up into a map of labels and expressions, and creates functions
* from the expressions that are suitable for execution by
* JsEvalContext.jsexec(). All that is returned as a flattened array
* of pairs of a String and a Function.
*
* @param {string} expr
*
* @return {Array}
*/
function jsEvalToValues(expr) {
// TODO(mesch): It is insufficient to split the values by simply
// finding semi-colons, as the semi-colon may be part of a string
// constant or escaped.
var ret = [];
var values = expr.split(REGEXP_pipe);//REGEXP_semicolon);
var tokens=[];
for (var i = 0, I = jsLength(values); i < I; ++i) {
// TAF: If we get an empty string as a token, it will be because we
// got an OR ('||') in the input and the regular expression incorrectly
// split it. Put the || back.
var token;
if (values[i]==='') {
token=tokens.pop();
token=token+" || "+values[++i];
tokens.push(token);
}
else {
tokens.push(values[i]);
}
}
for (i = 0, I = jsLength(tokens); i < I; ++i) {
var separator = tokens[i].indexOf(CHAR_equals);//CHAR_colon);
if (separator < 0) {
continue;
}
var label = stringTrim(tokens[i].substr(0, separator));
var value = jsEvalToFunction(tokens[i].substr(separator + 1));
ret.push(label, value);
}
return ret;
}
/**
* Parses the value of the jseval attribute of jstemplates: splits it
* up into a list of expressions, and creates functions from the
* expressions that are suitable for execution by
* JsEvalContext.jsexec(). All that is returned as an Array of
* Function.
*
* @param {string} expr
*
* @return {Array.<Function>}
*/
function jsEvalToExpressions(expr) {
var ret = [];
var values = expr.split(REGEXP_semicolon);
for (var i = 0, I = jsLength(values); i < I; ++i) {
if (values[i]) {
var value = jsEvalToFunction(values[i]);
ret.push(value);
}
}
return ret;
}
////////////////////////////////////////////////////////////////////////////
// jstemplate.js
////////////////////////////////////////////////////////////////////////////
/**
* Names of jstemplate attributes. These attributes are attached to
* normal HTML elements and bind expression context data to the HTML
* fragment that is used as template.
*/
// var ATT_select = 'jsselect';
// var ATT_instance = 'jsinstance';
// var ATT_display = 'jsdisplay';
// var ATT_values = 'jsvalues';
// var ATT_vars = 'jsvars';