1 // Copyright 2006 Google Inc.
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
7 // http://www.apache.org/licenses/LICENSE-2.0
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12 // implied. See the License for the specific language governing
13 // permissions and limitations under the License.
15 * Author: Steffen Meschkat <mesch@google.com>
17 * @fileoverview A simple formatter to project JavaScript data into
18 * HTML templates. The template is edited in place. I.e. in order to
19 * instantiate a template, clone it from the DOM first, and then
20 * process the cloned template. This allows for updating of templates:
21 * If the templates is processed again, changed values are merely
24 * NOTE(mesch): IE DOM doesn't have importNode().
26 * NOTE(mesch): The property name "length" must not be used in input
27 * data, see comment in jstSelect_().
32 * Names of jstemplate attributes. These attributes are attached to
33 * normal HTML elements and bind expression context data to the HTML
34 * fragment that is used as template.
36 var ATT_select
= 'jsselect';
37 var ATT_instance
= 'jsinstance';
38 var ATT_display
= 'jsdisplay';
39 var ATT_values
= 'jsvalues';
40 var ATT_vars
= 'jsvars';
41 var ATT_eval
= 'jseval';
42 var ATT_transclude
= 'transclude';
43 var ATT_content
= 'jscontent';
44 var ATT_skip
= 'jsskip';
48 * Name of the attribute that caches a reference to the parsed
49 * template processing attribute values on a template node.
51 var ATT_jstcache
= 'jstcache';
55 * Name of the property that caches the parsed template processing
56 * attribute values on a template node.
58 var PROP_jstcache
= '__jstcache';
62 * ID of the element that contains dynamically loaded jstemplates.
64 var STRING_jsts
= 'jsts';
68 * Un-inlined string literals, to avoid object creation in
71 var CHAR_asterisk
= '*';
72 var CHAR_dollar
= '$';
73 var CHAR_period
= '.';
74 var CHAR_ampersand
= '&';
75 var STRING_div
= 'div';
77 var STRING_asteriskzero
= '*0';
78 var STRING_zero
= '0';
82 * HTML template processor. Data values are bound to HTML templates
83 * using the attributes transclude, jsselect, jsdisplay, jscontent,
84 * jsvalues. The template is modifed in place. The values of those
85 * attributes are JavaScript expressions that are evaluated in the
86 * context of the data object fragment.
88 * @param {JsEvalContext} context Context created from the input data
91 * @param {Element} template DOM node of the template. This will be
92 * processed in place. After processing, it will still be a valid
93 * template that, if processed again with the same data, will remain
96 * @param {boolean} opt_debugging Optional flag to collect debugging
97 * information while processing the template. Only takes effect
100 function jstProcess(context
, template
, opt_debugging
) {
101 var processor
= new JstProcessor
;
102 JstProcessor
.prepareTemplate_(template
);
105 * Caches the document of the template node, so we don't have to
106 * access it through ownerDocument.
109 processor
.document_
= ownerDocument(template
);
111 processor
.run_(bindFully(processor
, processor
.jstProcessOuter_
,
117 * Internal class used by jstemplates to maintain context. This is
118 * necessary to process deep templates in Safari which has a
119 * relatively shallow maximum recursion depth of 100.
123 function JstProcessor() {
128 * Counter to generate node ids. These ids will be stored in
129 * ATT_jstcache and be used to lookup the preprocessed js attributes
130 * from the jstcache_. The id is stored in an attribute so it
131 * suvives cloneNode() and thus cloned template nodes can share the
135 JstProcessor
.jstid_
= 0;
139 * Map from jstid to processed js attributes.
142 JstProcessor
.jstcache_
= {};
145 * The neutral cache entry. Used for all nodes that don't have any
146 * jst attributes. We still set the jsid attribute on those nodes so
147 * we can avoid to look again for all the other jst attributes that
148 * aren't there. Remember: not only the processing of the js
149 * attribute values is expensive and we thus want to cache it. The
150 * access to the attributes on the Node in the first place is
153 JstProcessor
.jstcache_
[0] = {};
157 * Map from concatenated attribute string to jstid.
158 * The key is the concatenation of all jst atributes found on a node
159 * formatted as "name1=value1&name2=value2&...", in the order defined by
160 * JST_ATTRIBUTES. The value is the id of the jstcache_ entry that can
161 * be used for this node. This allows the reuse of cache entries in cases
162 * when a cached entry already exists for a given combination of attribute
163 * values. (For example when two different nodes in a template share the same
167 JstProcessor
.jstcacheattributes_
= {};
171 * Map for storing temporary attribute values in prepareNode_() so they don't
172 * have to be retrieved twice. (IE6 perf)
175 JstProcessor
.attributeValues_
= {};
179 * A list for storing non-empty attributes found on a node in prepareNode_().
180 * The array is global since it can be reused - this way there is no need to
181 * construct a new array object for each invocation. (IE6 perf)
184 JstProcessor
.attributeList_
= [];
188 * Prepares the template: preprocesses all jstemplate attributes.
190 * @param {Element} template
192 JstProcessor
.prepareTemplate_ = function(template
) {
193 if (!template
[PROP_jstcache
]) {
194 domTraverseElements(template
, function(node
) {
195 JstProcessor
.prepareNode_(node
);
202 * A list of attributes we use to specify jst processing instructions,
203 * and the functions used to parse their values.
205 * @type Array.<Array>
207 var JST_ATTRIBUTES
= [
208 [ ATT_select
, jsEvalToFunction
],
209 [ ATT_display
, jsEvalToFunction
],
210 [ ATT_values
, jsEvalToValues
],
211 [ ATT_vars
, jsEvalToValues
],
212 [ ATT_eval
, jsEvalToExpressions
],
213 [ ATT_transclude
, jsEvalToSelf
],
214 [ ATT_content
, jsEvalToFunction
],
215 [ ATT_skip
, jsEvalToFunction
]
220 * Prepares a single node: preprocesses all template attributes of the
221 * node, and if there are any, assigns a jsid attribute and stores the
222 * preprocessed attributes under the jsid in the jstcache.
224 * @param {Element} node
226 * @return {Object} The jstcache entry. The processed jst attributes
227 * are properties of this object. If the node has no jst attributes,
228 * returns an object with no properties (the jscache_[0] entry).
230 JstProcessor
.prepareNode_ = function(node
) {
231 // If the node already has a cache property, return it.
232 if (node
[PROP_jstcache
]) {
233 return node
[PROP_jstcache
];
236 // If it is not found, we always set the PROP_jstcache property on the node.
237 // Accessing the property is faster than executing getAttribute(). If we
238 // don't find the property on a node that was cloned in jstSelect_(), we
239 // will fall back to check for the attribute and set the property
242 // If the node has an attribute indexing a cache object, set it as a property
244 var jstid
= domGetAttribute(node
, ATT_jstcache
);
246 return node
[PROP_jstcache
] = JstProcessor
.jstcache_
[jstid
];
249 var attributeValues
= JstProcessor
.attributeValues_
;
250 var attributeList
= JstProcessor
.attributeList_
;
251 attributeList
.length
= 0;
253 // Look for interesting attributes.
254 for (var i
= 0, I
= jsLength(JST_ATTRIBUTES
); i
< I
; ++i
) {
255 var name
= JST_ATTRIBUTES
[i
][0];
256 var value
= domGetAttribute(node
, name
);
257 attributeValues
[name
] = value
;
259 attributeList
.push(name
+ "=" + value
);
263 // If none found, mark this node to prevent further inspection, and return
264 // an empty cache object.
265 if (attributeList
.length
== 0) {
266 domSetAttribute(node
, ATT_jstcache
, STRING_zero
);
267 return node
[PROP_jstcache
] = JstProcessor
.jstcache_
[0];
270 // If we already have a cache object corresponding to these attributes,
271 // annotate the node with it, and return it.
272 var attstring
= attributeList
.join(CHAR_ampersand
);
273 if (jstid
= JstProcessor
.jstcacheattributes_
[attstring
]) {
274 domSetAttribute(node
, ATT_jstcache
, jstid
);
275 return node
[PROP_jstcache
] = JstProcessor
.jstcache_
[jstid
];
278 // Otherwise, build a new cache object.
280 for (var i
= 0, I
= jsLength(JST_ATTRIBUTES
); i
< I
; ++i
) {
281 var att
= JST_ATTRIBUTES
[i
];
284 var value
= attributeValues
[name
];
286 jstcache
[name
] = parse(value
);
290 jstid
= STRING_empty
+ ++JstProcessor
.jstid_
;
291 domSetAttribute(node
, ATT_jstcache
, jstid
);
292 JstProcessor
.jstcache_
[jstid
] = jstcache
;
293 JstProcessor
.jstcacheattributes_
[attstring
] = jstid
;
295 return node
[PROP_jstcache
] = jstcache
;
300 * Runs the given function in our state machine.
302 * It's informative to view the set of all function calls as a tree:
304 * - edges are state transitions, implemented as calls to the pending
305 * functions in the stack.
306 * - pre-order function calls are downward edges (recursion into call).
307 * - post-order function calls are upward edges (return from call).
308 * - leaves are nodes which do not recurse.
309 * We represent the call tree as an array of array of calls, indexed as
310 * stack[depth][index]. Here [depth] indexes into the call stack, and
311 * [index] indexes into the call queue at that depth. We require a call
312 * queue so that a node may branch to more than one child
313 * (which will be called serially), typically due to a loop structure.
315 * @param {Function} f The first function to run.
317 JstProcessor
.prototype.run_ = function(f
) {
321 * A stack of queues of pre-order calls.
322 * The inner arrays (constituent queues) are structured as
323 * [ arg2, arg1, method, arg2, arg1, method, ...]
324 * ie. a flattened array of methods with 2 arguments, in reverse order
325 * for efficient push/pop.
327 * The outer array is a stack of such queues.
329 * @type Array.<Array>
331 var calls
= me
.calls_
= [];
334 * The index into the queue for each depth. NOTE: Alternative would
335 * be to maintain the queues in reverse order (popping off of the
336 * end) but the repeated calls to .pop() consumed 90% of this
337 * function's execution time.
338 * @type Array.<number>
340 var queueIndices
= me
.queueIndices_
= [];
343 * A pool of empty arrays. Minimizes object allocation for IE6's benefit.
344 * @type Array.<Array>
346 var arrayPool
= me
.arrayPool_
= [];
349 var queue
, queueIndex
;
350 var method
, arg1
, arg2
;
352 while (calls
.length
) {
353 queue
= calls
[calls
.length
- 1];
354 queueIndex
= queueIndices
[queueIndices
.length
- 1];
355 if (queueIndex
>= queue
.length
) {
356 me
.recycleArray_(calls
.pop());
361 // Run the first function in the queue.
362 method
= queue
[queueIndex
++];
363 arg1
= queue
[queueIndex
++];
364 arg2
= queue
[queueIndex
++];
365 queueIndices
[queueIndices
.length
- 1] = queueIndex
;
366 method
.call(me
, arg1
, arg2
);
372 * Pushes one or more functions onto the stack. These will be run in sequence,
373 * interspersed with any recursive calls that they make.
375 * This method takes ownership of the given array!
377 * @param {Array} args Array of method calls structured as
378 * [ method, arg1, arg2, method, arg1, arg2, ... ]
380 JstProcessor
.prototype.push_ = function(args
) {
381 this.calls_
.push(args
);
382 this.queueIndices_
.push(0);
387 * Enable/disable debugging.
388 * @param {boolean} debugging New state
390 JstProcessor
.prototype.setDebugging = function(debugging
) {
394 JstProcessor
.prototype.createArray_ = function() {
395 if (this.arrayPool_
.length
) {
396 return this.arrayPool_
.pop();
403 JstProcessor
.prototype.recycleArray_ = function(array
) {
405 this.arrayPool_
.push(array
);
409 * Implements internals of jstProcess. This processes the two
410 * attributes transclude and jsselect, which replace or multiply
411 * elements, hence the name "outer". The remainder of the attributes
412 * is processed in jstProcessInner_(), below. That function
413 * jsProcessInner_() only processes attributes that affect an existing
414 * node, but doesn't create or destroy nodes, hence the name
415 * "inner". jstProcessInner_() is called through jstSelect_() if there
416 * is a jsselect attribute (possibly for newly created clones of the
417 * current template node), or directly from here if there is none.
419 * @param {JsEvalContext} context
421 * @param {Element} template
423 JstProcessor
.prototype.jstProcessOuter_ = function(context
, template
) {
426 var jstAttributes
= me
.jstAttributes_(template
);
428 var transclude
= jstAttributes
[ATT_transclude
];
430 var tr
= jstGetTemplate(transclude
);
432 domReplaceChild(tr
, template
);
433 var call
= me
.createArray_();
434 call
.push(me
.jstProcessOuter_
, context
, tr
);
437 domRemoveNode(template
);
442 var select
= jstAttributes
[ATT_select
];
444 me
.jstSelect_(context
, template
, select
);
446 me
.jstProcessInner_(context
, template
);
452 * Implements internals of jstProcess. This processes all attributes
453 * except transclude and jsselect. It is called either from
454 * jstSelect_() for nodes that have a jsselect attribute so that the
455 * jsselect attribute will not be processed again, or else directly
456 * from jstProcessOuter_(). See the comment on jstProcessOuter_() for
457 * an explanation of the name.
459 * @param {JsEvalContext} context
461 * @param {Element} template
463 JstProcessor
.prototype.jstProcessInner_ = function(context
, template
) {
466 var jstAttributes
= me
.jstAttributes_(template
);
468 // NOTE(mesch): See NOTE on ATT_content why this is a separate
469 // attribute, and not a special value in ATT_values.
470 var display
= jstAttributes
[ATT_display
];
472 var shouldDisplay
= context
.jsexec(display
, template
);
473 if (!shouldDisplay
) {
474 displayNone(template
);
477 displayDefault(template
);
480 // NOTE(mesch): jsvars is evaluated before jsvalues, because it's
481 // more useful to be able to use var values in attribute value
482 // expressions than vice versa.
483 var values
= jstAttributes
[ATT_vars
];
485 me
.jstVars_(context
, template
, values
);
488 values
= jstAttributes
[ATT_values
];
490 me
.jstValues_(context
, template
, values
);
493 // Evaluate expressions immediately. Useful for hooking callbacks
496 // NOTE(mesch): Evaluation order is sometimes significant, e.g. when
497 // the expression evaluated in jseval relies on the values set in
498 // jsvalues, so it needs to be evaluated *after*
499 // jsvalues. TODO(mesch): This is quite arbitrary, it would be
500 // better if this would have more necessity to it.
501 var expressions
= jstAttributes
[ATT_eval
];
503 for (var i
= 0, I
= jsLength(expressions
); i
< I
; ++i
) {
504 context
.jsexec(expressions
[i
], template
);
508 var skip
= jstAttributes
[ATT_skip
];
510 var shouldSkip
= context
.jsexec(skip
, template
);
511 if (shouldSkip
) return;
514 // NOTE(mesch): content is a separate attribute, instead of just a
515 // special value mentioned in values, for two reasons: (1) it is
516 // fairly common to have only mapped content, and writing
517 // content="expr" is shorter than writing values="content:expr", and
518 // (2) the presence of content actually terminates traversal, and we
519 // need to check for that. Display is a separate attribute for a
520 // reason similar to the second, in that its presence *may*
521 // terminate traversal.
522 var content
= jstAttributes
[ATT_content
];
524 me
.jstContent_(context
, template
, content
);
527 // Newly generated children should be ignored, so we explicitly
528 // store the children to be processed.
529 var queue
= me
.createArray_();
530 for (var c
= template
.firstChild
; c
; c
= c
.nextSibling
) {
531 if (c
.nodeType
== DOM_ELEMENT_NODE
) {
532 queue
.push(me
.jstProcessOuter_
, context
, c
);
535 if (queue
.length
) me
.push_(queue
);
541 * Implements the jsselect attribute: evalutes the value of the
542 * jsselect attribute in the current context, with the current
543 * variable bindings (see JsEvalContext.jseval()). If the value is an
544 * array, the current template node is multiplied once for every
545 * element in the array, with the array element being the context
546 * object. If the array is empty, or the value is undefined, then the
547 * current template node is dropped. If the value is not an array,
548 * then it is just made the context object.
550 * @param {JsEvalContext} context The current evaluation context.
552 * @param {Element} template The currently processed node of the template.
554 * @param {Function} select The javascript expression to evaluate.
556 * @notypecheck FIXME(hmitchell): See OCL6434950. instance and value need
559 JstProcessor
.prototype.jstSelect_ = function(context
, template
, select
) {
562 var value
= context
.jsexec(select
, template
);
564 // Enable reprocessing: if this template is reprocessed, then only
565 // fill the section instance here. Otherwise do the cardinal
566 // processing of a new template.
567 var instance
= domGetAttribute(template
, ATT_instance
);
569 var instanceLast
= false;
571 if (instance
.charAt(0) == CHAR_asterisk
) {
572 instance
= parseInt10(instance
.substr(1));
575 instance
= parseInt10(/** @type string */(instance
));
579 // The expression value instanceof Array is occasionally false for
580 // arrays, seen in Firefox. Thus we recognize an array as an object
581 // which is not null that has a length property. Notice that this
582 // also matches input data with a length property, so this property
583 // name should be avoided in input data.
584 var multiple
= isArray(value
);
585 var count
= multiple
? jsLength(value
) : 1;
586 var multipleEmpty
= (multiple
&& count
== 0);
590 // For an empty array, keep the first template instance and mark
591 // it last. Remove all other template instances.
593 domSetAttribute(template
, ATT_instance
, STRING_asteriskzero
);
594 displayNone(template
);
596 domRemoveNode(template
);
600 displayDefault(template
);
601 // For a non empty array, create as many template instances as
602 // are needed. If the template is first processed, as many
603 // template instances are needed as there are values in the
604 // array. If the template is reprocessed, new template instances
605 // are only needed if there are more array values than template
606 // instances. Those additional instances are created by
607 // replicating the last template instance.
609 // When the template is first processed, there is no jsinstance
610 // attribute. This is indicated by instance === null, except in
611 // opera it is instance === "". Notice also that the === is
612 // essential, because 0 == "", presumably via type coercion to
614 if (instance
=== null || instance
=== STRING_empty
||
615 (instanceLast
&& instance
< count
- 1)) {
616 // A queue of calls to push.
617 var queue
= me
.createArray_();
619 var instancesStart
= instance
|| 0;
621 for (i
= instancesStart
, I
= count
- 1; i
< I
; ++i
) {
622 var node
= domCloneNode(template
);
623 domInsertBefore(node
, template
);
625 jstSetInstance(/** @type Element */(node
), value
, i
);
626 clone
= context
.clone(value
[i
], i
, count
);
628 queue
.push(me
.jstProcessInner_
, clone
, node
,
629 JsEvalContext
.recycle
, clone
, null);
632 // Push the originally present template instance last to keep
633 // the order aligned with the DOM order, because the newly
634 // created template instances are inserted *before* the
635 // original instance.
636 jstSetInstance(template
, value
, i
);
637 clone
= context
.clone(value
[i
], i
, count
);
638 queue
.push(me
.jstProcessInner_
, clone
, template
,
639 JsEvalContext
.recycle
, clone
, null);
641 } else if (instance
< count
) {
642 var v
= value
[instance
];
644 jstSetInstance(template
, value
, instance
);
645 var clone
= context
.clone(v
, instance
, count
);
646 var queue
= me
.createArray_();
647 queue
.push(me
.jstProcessInner_
, clone
, template
,
648 JsEvalContext
.recycle
, clone
, null);
651 domRemoveNode(template
);
656 displayNone(template
);
658 displayDefault(template
);
659 var clone
= context
.clone(value
, 0, 1);
660 var queue
= me
.createArray_();
661 queue
.push(me
.jstProcessInner_
, clone
, template
,
662 JsEvalContext
.recycle
, clone
, null);
670 * Implements the jsvars attribute: evaluates each of the values and
671 * assigns them to variables in the current context. Similar to
672 * jsvalues, except that all values are treated as vars, independent
675 * @param {JsEvalContext} context Current evaluation context.
677 * @param {Element} template Currently processed template node.
679 * @param {Array} values Processed value of the jsvalues attribute: a
680 * flattened array of pairs. The second element in the pair is a
681 * function that can be passed to jsexec() for evaluation in the
682 * current jscontext, and the first element is the variable name that
683 * the value returned by jsexec is assigned to.
685 JstProcessor
.prototype.jstVars_ = function(context
, template
, values
) {
686 for (var i
= 0, I
= jsLength(values
); i
< I
; i
+= 2) {
687 var label
= values
[i
];
688 var value
= context
.jsexec(values
[i
+1], template
);
689 context
.setVariable(label
, value
);
695 * Implements the jsvalues attribute: evaluates each of the values and
696 * assigns them to variables in the current context (if the name
697 * starts with '$', javascript properties of the current template node
698 * (if the name starts with '.'), or DOM attributes of the current
699 * template node (otherwise). Since DOM attribute values are always
700 * strings, the value is coerced to string in the latter case,
701 * otherwise it's the uncoerced javascript value.
703 * @param {JsEvalContext} context Current evaluation context.
705 * @param {Element} template Currently processed template node.
707 * @param {Array} values Processed value of the jsvalues attribute: a
708 * flattened array of pairs. The second element in the pair is a
709 * function that can be passed to jsexec() for evaluation in the
710 * current jscontext, and the first element is the label that
711 * determines where the value returned by jsexec is assigned to.
713 JstProcessor
.prototype.jstValues_ = function(context
, template
, values
) {
714 for (var i
= 0, I
= jsLength(values
); i
< I
; i
+= 2) {
715 var label
= values
[i
];
716 var value
= context
.jsexec(values
[i
+1], template
);
718 if (label
.charAt(0) == CHAR_dollar
) {
719 // A jsvalues entry whose name starts with $ sets a local
721 context
.setVariable(label
, value
);
723 } else if (label
.charAt(0) == CHAR_period
) {
724 // A jsvalues entry whose name starts with . sets a property of
725 // the current template node. The name may have further dot
726 // separated components, which are translated into namespace
727 // objects. This specifically allows to set properties on .style
728 // using jsvalues. NOTE(mesch): Setting the style attribute has
729 // no effect in IE and hence should not be done anyway.
730 var nameSpaceLabel
= label
.substr(1).split(CHAR_period
);
731 var nameSpaceObject
= template
;
732 var nameSpaceDepth
= jsLength(nameSpaceLabel
);
733 for (var j
= 0, J
= nameSpaceDepth
- 1; j
< J
; ++j
) {
734 var jLabel
= nameSpaceLabel
[j
];
735 if (!nameSpaceObject
[jLabel
]) {
736 nameSpaceObject
[jLabel
] = {};
738 nameSpaceObject
= nameSpaceObject
[jLabel
];
740 nameSpaceObject
[nameSpaceLabel
[nameSpaceDepth
- 1]] = value
;
743 // Any other jsvalues entry sets an attribute of the current
745 if (typeof value
== TYPE_boolean
) {
746 // Handle boolean values that are set as attributes specially,
747 // according to the XML/HTML convention.
749 domSetAttribute(template
, label
, label
);
751 domRemoveAttribute(template
, label
);
754 domSetAttribute(template
, label
, STRING_empty
+ value
);
762 * Implements the jscontent attribute. Evalutes the expression in
763 * jscontent in the current context and with the current variables,
764 * and assigns its string value to the content of the current template
767 * @param {JsEvalContext} context Current evaluation context.
769 * @param {Element} template Currently processed template node.
771 * @param {Function} content Processed value of the jscontent
774 JstProcessor
.prototype.jstContent_ = function(context
, template
, content
) {
775 // NOTE(mesch): Profiling shows that this method costs significant
776 // time. In jstemplate_perf.html, it's about 50%. I tried to replace
777 // by HTML escaping and assignment to innerHTML, but that was even
779 var value
= STRING_empty
+ context
.jsexec(content
, template
);
780 // Prevent flicker when refreshing a template and the value doesn't
782 if (template
.innerHTML
== value
) {
785 while (template
.firstChild
) {
786 domRemoveNode(template
.firstChild
);
788 var t
= domCreateTextNode(this.document_
, value
);
789 domAppendChild(template
, t
);
794 * Caches access to and parsing of template processing attributes. If
795 * domGetAttribute() is called every time a template attribute value
796 * is used, it takes more than 10% of the time.
798 * @param {Element} template A DOM element node of the template.
800 * @return {Object} A javascript object that has all js template
801 * processing attribute values of the node as properties.
803 JstProcessor
.prototype.jstAttributes_ = function(template
) {
804 if (template
[PROP_jstcache
]) {
805 return template
[PROP_jstcache
];
808 var jstid
= domGetAttribute(template
, ATT_jstcache
);
810 return template
[PROP_jstcache
] = JstProcessor
.jstcache_
[jstid
];
813 return JstProcessor
.prepareNode_(template
);
818 * Helps to implement the transclude attribute, and is the initial
819 * call to get hold of a template from its ID.
821 * If the ID is not present in the DOM, and opt_loadHtmlFn is specified, this
822 * function will call that function and add the result to the DOM, before
823 * returning the template.
825 * @param {string} name The ID of the HTML element used as template.
826 * @param {Function} opt_loadHtmlFn A function which, when called, will return
827 * HTML that contains an element whose ID is 'name'.
829 * @return {Element|null} The DOM node of the template. (Only element nodes
830 * can be found by ID, hence it's a Element.)
832 function jstGetTemplate(name
, opt_loadHtmlFn
) {
835 if (opt_loadHtmlFn
) {
836 section
= jstLoadTemplateIfNotPresent(doc
, name
, opt_loadHtmlFn
);
838 section
= domGetElementById(doc
, name
);
841 JstProcessor
.prepareTemplate_(section
);
842 var ret
= domCloneElement(section
);
843 domRemoveAttribute(ret
, STRING_id
);
851 * This function is the same as 'jstGetTemplate' but, if the template
852 * does not exist, throw an exception.
854 * @param {string} name The ID of the HTML element used as template.
855 * @param {Function} opt_loadHtmlFn A function which, when called, will return
856 * HTML that contains an element whose ID is 'name'.
858 * @return {Element} The DOM node of the template. (Only element nodes
859 * can be found by ID, hence it's a Element.)
861 function jstGetTemplateOrDie(name
, opt_loadHtmlFn
) {
862 var x
= jstGetTemplate(name
, opt_loadHtmlFn
);
864 return /** @type Element */(x
);
869 * If an element with id 'name' is not present in the document, call loadHtmlFn
870 * and insert the result into the DOM.
872 * @param {Document} doc
873 * @param {string} name
874 * @param {Function} loadHtmlFn A function that returns HTML to be inserted
876 * @param {string} opt_target The id of a DOM object under which to attach the
877 * HTML once it's inserted. An object with this id is created if it does not
879 * @return {Element} The node whose id is 'name'
881 function jstLoadTemplateIfNotPresent(doc
, name
, loadHtmlFn
, opt_target
) {
882 var section
= domGetElementById(doc
, name
);
886 // Load any necessary HTML and try again.
887 jstLoadTemplate_(doc
, loadHtmlFn(), opt_target
|| STRING_jsts
);
888 var section
= domGetElementById(doc
, name
);
890 log("Error: jstGetTemplate was provided with opt_loadHtmlFn, " +
891 "but that function did not provide the id '" + name
+ "'.");
893 return /** @type Element */(section
);
898 * Loads the given HTML text into the given document, so that
899 * jstGetTemplate can find it.
901 * We append it to the element identified by targetId, which is hidden.
902 * If it doesn't exist, it is created.
904 * @param {Document} doc The document to create the template in.
906 * @param {string} html HTML text to be inserted into the document.
908 * @param {string} targetId The id of a DOM object under which to attach the
909 * HTML once it's inserted. An object with this id is created if it does not
912 function jstLoadTemplate_(doc
, html
, targetId
) {
913 var existing_target
= domGetElementById(doc
, targetId
);
915 if (!existing_target
) {
916 target
= domCreateElement(doc
, STRING_div
);
917 target
.id
= targetId
;
919 positionAbsolute(target
);
920 domAppendChild(doc
.body
, target
);
922 target
= existing_target
;
924 var div
= domCreateElement(doc
, STRING_div
);
925 target
.appendChild(div
);
926 div
.innerHTML
= html
;
931 * Sets the jsinstance attribute on a node according to its context.
933 * @param {Element} template The template DOM node to set the instance
936 * @param {Array} values The current input context, the array of
937 * values of which the template node will render one instance.
939 * @param {number} index The index of this template node in values.
941 function jstSetInstance(template
, values
, index
) {
942 if (index
== jsLength(values
) - 1) {
943 domSetAttribute(template
, ATT_instance
, CHAR_asterisk
+ index
);
945 domSetAttribute(template
, ATT_instance
, STRING_empty
+ index
);
951 * Log the current state.
952 * @param {string} caller An identifier for the caller of .log_.
953 * @param {Element} template The template node being processed.
954 * @param {Object} jstAttributeValues The jst attributes of the template node.
956 JstProcessor
.prototype.logState_ = function(
957 caller
, template
, jstAttributeValues
) {
962 * Retrieve the processing logs.
963 * @return {Array.<string>} The processing logs.
965 JstProcessor
.prototype.getLogs = function() {