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 if (MAPS_DEBUG && opt_debugging) {
103 processor.setDebugging(opt_debugging);
105 JstProcessor.prepareTemplate_(template);
108 * Caches the document of the template node, so we don't have to
109 * access it through ownerDocument.
112 processor.document_ = ownerDocument(template);
114 processor.run_(bindFully(processor, processor.jstProcessOuter_,
116 if (MAPS_DEBUG && opt_debugging) {
117 log('jstProcess:' + '\n' + processor.getLogs().join('\n'));
123 * Internal class used by jstemplates to maintain context. This is
124 * necessary to process deep templates in Safari which has a
125 * relatively shallow maximum recursion depth of 100.
129 function JstProcessor() {
132 * An array of logging messages. These are collected during processing
133 * and dumped to the console at the end.
134 * @type Array.<string>
142 * Counter to generate node ids. These ids will be stored in
143 * ATT_jstcache and be used to lookup the preprocessed js attributes
144 * from the jstcache_. The id is stored in an attribute so it
145 * suvives cloneNode() and thus cloned template nodes can share the
149 JstProcessor.jstid_ = 0;
153 * Map from jstid to processed js attributes.
156 JstProcessor.jstcache_ = {};
159 * The neutral cache entry. Used for all nodes that don't have any
160 * jst attributes. We still set the jsid attribute on those nodes so
161 * we can avoid to look again for all the other jst attributes that
162 * aren't there. Remember: not only the processing of the js
163 * attribute values is expensive and we thus want to cache it. The
164 * access to the attributes on the Node in the first place is
167 JstProcessor.jstcache_[0] = {};
171 * Map from concatenated attribute string to jstid.
172 * The key is the concatenation of all jst atributes found on a node
173 * formatted as "name1=value1&name2=value2&...", in the order defined by
174 * JST_ATTRIBUTES. The value is the id of the jstcache_ entry that can
175 * be used for this node. This allows the reuse of cache entries in cases
176 * when a cached entry already exists for a given combination of attribute
177 * values. (For example when two different nodes in a template share the same
181 JstProcessor.jstcacheattributes_ = {};
185 * Map for storing temporary attribute values in prepareNode_() so they don't
186 * have to be retrieved twice. (IE6 perf)
189 JstProcessor.attributeValues_ = {};
193 * A list for storing non-empty attributes found on a node in prepareNode_().
194 * The array is global since it can be reused - this way there is no need to
195 * construct a new array object for each invocation. (IE6 perf)
198 JstProcessor.attributeList_ = [];
202 * Prepares the template: preprocesses all jstemplate attributes.
204 * @param {Element} template
206 JstProcessor.prepareTemplate_ = function(template) {
207 if (!template[PROP_jstcache]) {
208 domTraverseElements(template, function(node) {
209 JstProcessor.prepareNode_(node);
216 * A list of attributes we use to specify jst processing instructions,
217 * and the functions used to parse their values.
219 * @type Array.<Array>
221 var JST_ATTRIBUTES = [
222 [ ATT_select, jsEvalToFunction ],
223 [ ATT_display, jsEvalToFunction ],
224 [ ATT_values, jsEvalToValues ],
225 [ ATT_vars, jsEvalToValues ],
226 [ ATT_eval, jsEvalToExpressions ],
227 [ ATT_transclude, jsEvalToSelf ],
228 [ ATT_content, jsEvalToFunction ],
229 [ ATT_skip, jsEvalToFunction ]
234 * Prepares a single node: preprocesses all template attributes of the
235 * node, and if there are any, assigns a jsid attribute and stores the
236 * preprocessed attributes under the jsid in the jstcache.
238 * @param {Element} node
240 * @return {Object} The jstcache entry. The processed jst attributes
241 * are properties of this object. If the node has no jst attributes,
242 * returns an object with no properties (the jscache_[0] entry).
244 JstProcessor.prepareNode_ = function(node) {
245 // If the node already has a cache property, return it.
246 if (node[PROP_jstcache]) {
247 return node[PROP_jstcache];
250 // If it is not found, we always set the PROP_jstcache property on the node.
251 // Accessing the property is faster than executing getAttribute(). If we
252 // don't find the property on a node that was cloned in jstSelect_(), we
253 // will fall back to check for the attribute and set the property
256 // If the node has an attribute indexing a cache object, set it as a property
258 var jstid = domGetAttribute(node, ATT_jstcache);
260 return node[PROP_jstcache] = JstProcessor.jstcache_[jstid];
263 var attributeValues = JstProcessor.attributeValues_;
264 var attributeList = JstProcessor.attributeList_;
265 attributeList.length = 0;
267 // Look for interesting attributes.
268 for (var i = 0, I = jsLength(JST_ATTRIBUTES); i < I; ++i) {
269 var name = JST_ATTRIBUTES[i][0];
270 var value = domGetAttribute(node, name);
271 attributeValues[name] = value;
273 attributeList.push(name + "=" + value);
277 // If none found, mark this node to prevent further inspection, and return
278 // an empty cache object.
279 if (attributeList.length == 0) {
280 domSetAttribute(node, ATT_jstcache, STRING_zero);
281 return node[PROP_jstcache] = JstProcessor.jstcache_[0];
284 // If we already have a cache object corresponding to these attributes,
285 // annotate the node with it, and return it.
286 var attstring = attributeList.join(CHAR_ampersand);
287 if (jstid = JstProcessor.jstcacheattributes_[attstring]) {
288 domSetAttribute(node, ATT_jstcache, jstid);
289 return node[PROP_jstcache] = JstProcessor.jstcache_[jstid];
292 // Otherwise, build a new cache object.
294 for (var i = 0, I = jsLength(JST_ATTRIBUTES); i < I; ++i) {
295 var att = JST_ATTRIBUTES[i];
298 var value = attributeValues[name];
300 jstcache[name] = parse(value);
302 jstcache.jstAttributeValues = jstcache.jstAttributeValues || {};
303 jstcache.jstAttributeValues[name] = value;
308 jstid = STRING_empty + ++JstProcessor.jstid_;
309 domSetAttribute(node, ATT_jstcache, jstid);
310 JstProcessor.jstcache_[jstid] = jstcache;
311 JstProcessor.jstcacheattributes_[attstring] = jstid;
313 return node[PROP_jstcache] = jstcache;
318 * Runs the given function in our state machine.
320 * It's informative to view the set of all function calls as a tree:
322 * - edges are state transitions, implemented as calls to the pending
323 * functions in the stack.
324 * - pre-order function calls are downward edges (recursion into call).
325 * - post-order function calls are upward edges (return from call).
326 * - leaves are nodes which do not recurse.
327 * We represent the call tree as an array of array of calls, indexed as
328 * stack[depth][index]. Here [depth] indexes into the call stack, and
329 * [index] indexes into the call queue at that depth. We require a call
330 * queue so that a node may branch to more than one child
331 * (which will be called serially), typically due to a loop structure.
333 * @param {Function} f The first function to run.
335 JstProcessor.prototype.run_ = function(f) {
339 * A stack of queues of pre-order calls.
340 * The inner arrays (constituent queues) are structured as
341 * [ arg2, arg1, method, arg2, arg1, method, ...]
342 * ie. a flattened array of methods with 2 arguments, in reverse order
343 * for efficient push/pop.
345 * The outer array is a stack of such queues.
347 * @type Array.<Array>
349 var calls = me.calls_ = [];
352 * The index into the queue for each depth. NOTE: Alternative would
353 * be to maintain the queues in reverse order (popping off of the
354 * end) but the repeated calls to .pop() consumed 90% of this
355 * function's execution time.
356 * @type Array.<number>
358 var queueIndices = me.queueIndices_ = [];
361 * A pool of empty arrays. Minimizes object allocation for IE6's benefit.
362 * @type Array.<Array>
364 var arrayPool = me.arrayPool_ = [];
367 var queue, queueIndex;
368 var method, arg1, arg2;
370 while (calls.length) {
371 queue = calls[calls.length - 1];
372 queueIndex = queueIndices[queueIndices.length - 1];
373 if (queueIndex >= queue.length) {
374 me.recycleArray_(calls.pop());
379 // Run the first function in the queue.
380 method = queue[queueIndex++];
381 arg1 = queue[queueIndex++];
382 arg2 = queue[queueIndex++];
383 queueIndices[queueIndices.length - 1] = queueIndex;
384 method.call(me, arg1, arg2);
390 * Pushes one or more functions onto the stack. These will be run in sequence,
391 * interspersed with any recursive calls that they make.
393 * This method takes ownership of the given array!
395 * @param {Array} args Array of method calls structured as
396 * [ method, arg1, arg2, method, arg1, arg2, ... ]
398 JstProcessor.prototype.push_ = function(args) {
399 this.calls_.push(args);
400 this.queueIndices_.push(0);
405 * Enable/disable debugging.
406 * @param {boolean} debugging New state
408 JstProcessor.prototype.setDebugging = function(debugging) {
410 this.debugging_ = debugging;
415 JstProcessor.prototype.createArray_ = function() {
416 if (this.arrayPool_.length) {
417 return this.arrayPool_.pop();
424 JstProcessor.prototype.recycleArray_ = function(array) {
426 this.arrayPool_.push(array);
430 * Implements internals of jstProcess. This processes the two
431 * attributes transclude and jsselect, which replace or multiply
432 * elements, hence the name "outer". The remainder of the attributes
433 * is processed in jstProcessInner_(), below. That function
434 * jsProcessInner_() only processes attributes that affect an existing
435 * node, but doesn't create or destroy nodes, hence the name
436 * "inner". jstProcessInner_() is called through jstSelect_() if there
437 * is a jsselect attribute (possibly for newly created clones of the
438 * current template node), or directly from here if there is none.
440 * @param {JsEvalContext} context
442 * @param {Element} template
444 JstProcessor.prototype.jstProcessOuter_ = function(context, template) {
447 var jstAttributes = me.jstAttributes_(template);
448 if (MAPS_DEBUG && me.debugging_) {
449 me.logState_('Outer', template, jstAttributes.jstAttributeValues);
452 var transclude = jstAttributes[ATT_transclude];
454 var tr = jstGetTemplate(transclude);
456 domReplaceChild(tr, template);
457 var call = me.createArray_();
458 call.push(me.jstProcessOuter_, context, tr);
461 domRemoveNode(template);
466 var select = jstAttributes[ATT_select];
468 me.jstSelect_(context, template, select);
470 me.jstProcessInner_(context, template);
476 * Implements internals of jstProcess. This processes all attributes
477 * except transclude and jsselect. It is called either from
478 * jstSelect_() for nodes that have a jsselect attribute so that the
479 * jsselect attribute will not be processed again, or else directly
480 * from jstProcessOuter_(). See the comment on jstProcessOuter_() for
481 * an explanation of the name.
483 * @param {JsEvalContext} context
485 * @param {Element} template
487 JstProcessor.prototype.jstProcessInner_ = function(context, template) {
490 var jstAttributes = me.jstAttributes_(template);
491 if (MAPS_DEBUG && me.debugging_) {
492 me.logState_('Inner', template, jstAttributes.jstAttributeValues);
495 // NOTE(mesch): See NOTE on ATT_content why this is a separate
496 // attribute, and not a special value in ATT_values.
497 var display = jstAttributes[ATT_display];
499 var shouldDisplay = context.jsexec(display, template);
500 if (MAPS_DEBUG && me.debugging_) {
501 me.logs_.push(ATT_display + ': ' + shouldDisplay + '<br/>');
503 if (!shouldDisplay) {
504 displayNone(template);
507 displayDefault(template);
510 // NOTE(mesch): jsvars is evaluated before jsvalues, because it's
511 // more useful to be able to use var values in attribute value
512 // expressions than vice versa.
513 var values = jstAttributes[ATT_vars];
515 me.jstVars_(context, template, values);
518 values = jstAttributes[ATT_values];
520 me.jstValues_(context, template, values);
523 // Evaluate expressions immediately. Useful for hooking callbacks
526 // NOTE(mesch): Evaluation order is sometimes significant, e.g. when
527 // the expression evaluated in jseval relies on the values set in
528 // jsvalues, so it needs to be evaluated *after*
529 // jsvalues. TODO(mesch): This is quite arbitrary, it would be
530 // better if this would have more necessity to it.
531 var expressions = jstAttributes[ATT_eval];
533 for (var i = 0, I = jsLength(expressions); i < I; ++i) {
534 context.jsexec(expressions[i], template);
538 var skip = jstAttributes[ATT_skip];
540 var shouldSkip = context.jsexec(skip, template);
541 if (MAPS_DEBUG && me.debugging_) {
542 me.logs_.push(ATT_skip + ': ' + shouldSkip + '<br/>');
544 if (shouldSkip) return;
547 // NOTE(mesch): content is a separate attribute, instead of just a
548 // special value mentioned in values, for two reasons: (1) it is
549 // fairly common to have only mapped content, and writing
550 // content="expr" is shorter than writing values="content:expr", and
551 // (2) the presence of content actually terminates traversal, and we
552 // need to check for that. Display is a separate attribute for a
553 // reason similar to the second, in that its presence *may*
554 // terminate traversal.
555 var content = jstAttributes[ATT_content];
557 me.jstContent_(context, template, content);
560 // Newly generated children should be ignored, so we explicitly
561 // store the children to be processed.
562 var queue = me.createArray_();
563 for (var c = template.firstChild; c; c = c.nextSibling) {
564 if (c.nodeType == DOM_ELEMENT_NODE) {
565 queue.push(me.jstProcessOuter_, context, c);
568 if (queue.length) me.push_(queue);
574 * Implements the jsselect attribute: evalutes the value of the
575 * jsselect attribute in the current context, with the current
576 * variable bindings (see JsEvalContext.jseval()). If the value is an
577 * array, the current template node is multiplied once for every
578 * element in the array, with the array element being the context
579 * object. If the array is empty, or the value is undefined, then the
580 * current template node is dropped. If the value is not an array,
581 * then it is just made the context object.
583 * @param {JsEvalContext} context The current evaluation context.
585 * @param {Element} template The currently processed node of the template.
587 * @param {Function} select The javascript expression to evaluate.
589 * @notypecheck FIXME(hmitchell): See OCL6434950. instance and value need
592 JstProcessor.prototype.jstSelect_ = function(context, template, select) {
595 var value = context.jsexec(select, template);
597 // Enable reprocessing: if this template is reprocessed, then only
598 // fill the section instance here. Otherwise do the cardinal
599 // processing of a new template.
600 var instance = domGetAttribute(template, ATT_instance);
602 var instanceLast = false;
604 if (instance.charAt(0) == CHAR_asterisk) {
605 instance = parseInt10(instance.substr(1));
608 instance = parseInt10(/** @type string */(instance));
612 // The expression value instanceof Array is occasionally false for
613 // arrays, seen in Firefox. Thus we recognize an array as an object
614 // which is not null that has a length property. Notice that this
615 // also matches input data with a length property, so this property
616 // name should be avoided in input data.
617 var multiple = isArray(value);
618 var count = multiple ? jsLength(value) : 1;
619 var multipleEmpty = (multiple && count == 0);
623 // For an empty array, keep the first template instance and mark
624 // it last. Remove all other template instances.
626 domSetAttribute(template, ATT_instance, STRING_asteriskzero);
627 displayNone(template);
629 domRemoveNode(template);
633 displayDefault(template);
634 // For a non empty array, create as many template instances as
635 // are needed. If the template is first processed, as many
636 // template instances are needed as there are values in the
637 // array. If the template is reprocessed, new template instances
638 // are only needed if there are more array values than template
639 // instances. Those additional instances are created by
640 // replicating the last template instance.
642 // When the template is first processed, there is no jsinstance
643 // attribute. This is indicated by instance === null, except in
644 // opera it is instance === "". Notice also that the === is
645 // essential, because 0 == "", presumably via type coercion to
647 if (instance === null || instance === STRING_empty ||
648 (instanceLast && instance < count - 1)) {
649 // A queue of calls to push.
650 var queue = me.createArray_();
652 var instancesStart = instance || 0;
654 for (i = instancesStart, I = count - 1; i < I; ++i) {
655 var node = domCloneNode(template);
656 domInsertBefore(node, template);
658 jstSetInstance(/** @type Element */(node), value, i);
659 clone = context.clone(value[i], i, count);
661 queue.push(me.jstProcessInner_, clone, node,
662 JsEvalContext.recycle, clone, null);
665 // Push the originally present template instance last to keep
666 // the order aligned with the DOM order, because the newly
667 // created template instances are inserted *before* the
668 // original instance.
669 jstSetInstance(template, value, i);
670 clone = context.clone(value[i], i, count);
671 queue.push(me.jstProcessInner_, clone, template,
672 JsEvalContext.recycle, clone, null);
674 } else if (instance < count) {
675 var v = value[instance];
677 jstSetInstance(template, value, instance);
678 var clone = context.clone(v, instance, count);
679 var queue = me.createArray_();
680 queue.push(me.jstProcessInner_, clone, template,
681 JsEvalContext.recycle, clone, null);
684 domRemoveNode(template);
689 displayNone(template);
691 displayDefault(template);
692 var clone = context.clone(value, 0, 1);
693 var queue = me.createArray_();
694 queue.push(me.jstProcessInner_, clone, template,
695 JsEvalContext.recycle, clone, null);
703 * Implements the jsvars attribute: evaluates each of the values and
704 * assigns them to variables in the current context. Similar to
705 * jsvalues, except that all values are treated as vars, independent
708 * @param {JsEvalContext} context Current evaluation context.
710 * @param {Element} template Currently processed template node.
712 * @param {Array} values Processed value of the jsvalues attribute: a
713 * flattened array of pairs. The second element in the pair is a
714 * function that can be passed to jsexec() for evaluation in the
715 * current jscontext, and the first element is the variable name that
716 * the value returned by jsexec is assigned to.
718 JstProcessor.prototype.jstVars_ = function(context, template, values) {
719 for (var i = 0, I = jsLength(values); i < I; i += 2) {
720 var label = values[i];
721 var value = context.jsexec(values[i+1], template);
722 context.setVariable(label, value);
728 * Implements the jsvalues attribute: evaluates each of the values and
729 * assigns them to variables in the current context (if the name
730 * starts with '$', javascript properties of the current template node
731 * (if the name starts with '.'), or DOM attributes of the current
732 * template node (otherwise). Since DOM attribute values are always
733 * strings, the value is coerced to string in the latter case,
734 * otherwise it's the uncoerced javascript value.
736 * @param {JsEvalContext} context Current evaluation context.
738 * @param {Element} template Currently processed template node.
740 * @param {Array} values Processed value of the jsvalues attribute: a
741 * flattened array of pairs. The second element in the pair is a
742 * function that can be passed to jsexec() for evaluation in the
743 * current jscontext, and the first element is the label that
744 * determines where the value returned by jsexec is assigned to.
746 JstProcessor.prototype.jstValues_ = function(context, template, values) {
747 for (var i = 0, I = jsLength(values); i < I; i += 2) {
748 var label = values[i];
749 var value = context.jsexec(values[i+1], template);
751 if (label.charAt(0) == CHAR_dollar) {
752 // A jsvalues entry whose name starts with $ sets a local
754 context.setVariable(label, value);
756 } else if (label.charAt(0) == CHAR_period) {
757 // A jsvalues entry whose name starts with . sets a property of
758 // the current template node. The name may have further dot
759 // separated components, which are translated into namespace
760 // objects. This specifically allows to set properties on .style
761 // using jsvalues. NOTE(mesch): Setting the style attribute has
762 // no effect in IE and hence should not be done anyway.
763 var nameSpaceLabel = label.substr(1).split(CHAR_period);
764 var nameSpaceObject = template;
765 var nameSpaceDepth = jsLength(nameSpaceLabel);
766 for (var j = 0, J = nameSpaceDepth - 1; j < J; ++j) {
767 var jLabel = nameSpaceLabel[j];
768 if (!nameSpaceObject[jLabel]) {
769 nameSpaceObject[jLabel] = {};
771 nameSpaceObject = nameSpaceObject[jLabel];
773 nameSpaceObject[nameSpaceLabel[nameSpaceDepth - 1]] = value;
776 // Any other jsvalues entry sets an attribute of the current
778 if (typeof value == TYPE_boolean) {
779 // Handle boolean values that are set as attributes specially,
780 // according to the XML/HTML convention.
782 domSetAttribute(template, label, label);
784 domRemoveAttribute(template, label);
787 domSetAttribute(template, label, STRING_empty + value);
795 * Implements the jscontent attribute. Evalutes the expression in
796 * jscontent in the current context and with the current variables,
797 * and assigns its string value to the content of the current template
800 * @param {JsEvalContext} context Current evaluation context.
802 * @param {Element} template Currently processed template node.
804 * @param {Function} content Processed value of the jscontent
807 JstProcessor.prototype.jstContent_ = function(context, template, content) {
808 // NOTE(mesch): Profiling shows that this method costs significant
809 // time. In jstemplate_perf.html, it's about 50%. I tried to replace
810 // by HTML escaping and assignment to innerHTML, but that was even
812 var value = STRING_empty + context.jsexec(content, template);
813 // Prevent flicker when refreshing a template and the value doesn't
815 if (template.innerHTML == value) {
818 while (template.firstChild) {
819 domRemoveNode(template.firstChild);
821 var t = domCreateTextNode(this.document_, value);
822 domAppendChild(template, t);
827 * Caches access to and parsing of template processing attributes. If
828 * domGetAttribute() is called every time a template attribute value
829 * is used, it takes more than 10% of the time.
831 * @param {Element} template A DOM element node of the template.
833 * @return {Object} A javascript object that has all js template
834 * processing attribute values of the node as properties.
836 JstProcessor.prototype.jstAttributes_ = function(template) {
837 if (template[PROP_jstcache]) {
838 return template[PROP_jstcache];
841 var jstid = domGetAttribute(template, ATT_jstcache);
843 return template[PROP_jstcache] = JstProcessor.jstcache_[jstid];
846 return JstProcessor.prepareNode_(template);
851 * Helps to implement the transclude attribute, and is the initial
852 * call to get hold of a template from its ID.
854 * If the ID is not present in the DOM, and opt_loadHtmlFn is specified, this
855 * function will call that function and add the result to the DOM, before
856 * returning the template.
858 * @param {string} name The ID of the HTML element used as template.
859 * @param {Function} opt_loadHtmlFn A function which, when called, will return
860 * HTML that contains an element whose ID is 'name'.
862 * @return {Element|null} The DOM node of the template. (Only element nodes
863 * can be found by ID, hence it's a Element.)
865 function jstGetTemplate(name, opt_loadHtmlFn) {
868 if (opt_loadHtmlFn) {
869 section = jstLoadTemplateIfNotPresent(doc, name, opt_loadHtmlFn);
871 section = domGetElementById(doc, name);
874 JstProcessor.prepareTemplate_(section);
875 var ret = domCloneElement(section);
876 domRemoveAttribute(ret, STRING_id);
884 * This function is the same as 'jstGetTemplate' but, if the template
885 * does not exist, throw an exception.
887 * @param {string} name The ID of the HTML element used as template.
888 * @param {Function} opt_loadHtmlFn A function which, when called, will return
889 * HTML that contains an element whose ID is 'name'.
891 * @return {Element} The DOM node of the template. (Only element nodes
892 * can be found by ID, hence it's a Element.)
894 function jstGetTemplateOrDie(name, opt_loadHtmlFn) {
895 var x = jstGetTemplate(name, opt_loadHtmlFn);
897 return /** @type Element */(x);
902 * If an element with id 'name' is not present in the document, call loadHtmlFn
903 * and insert the result into the DOM.
905 * @param {Document} doc
906 * @param {string} name
907 * @param {Function} loadHtmlFn A function that returns HTML to be inserted
909 * @param {string} opt_target The id of a DOM object under which to attach the
910 * HTML once it's inserted. An object with this id is created if it does not
912 * @return {Element} The node whose id is 'name'
914 function jstLoadTemplateIfNotPresent(doc, name, loadHtmlFn, opt_target) {
915 var section = domGetElementById(doc, name);
919 // Load any necessary HTML and try again.
920 jstLoadTemplate_(doc, loadHtmlFn(), opt_target || STRING_jsts);
921 var section = domGetElementById(doc, name);
923 log("Error: jstGetTemplate was provided with opt_loadHtmlFn, " +
924 "but that function did not provide the id '" + name + "'.");
926 return /** @type Element */(section);
931 * Loads the given HTML text into the given document, so that
932 * jstGetTemplate can find it.
934 * We append it to the element identified by targetId, which is hidden.
935 * If it doesn't exist, it is created.
937 * @param {Document} doc The document to create the template in.
939 * @param {string} html HTML text to be inserted into the document.
941 * @param {string} targetId The id of a DOM object under which to attach the
942 * HTML once it's inserted. An object with this id is created if it does not
945 function jstLoadTemplate_(doc, html, targetId) {
946 var existing_target = domGetElementById(doc, targetId);
948 if (!existing_target) {
949 target = domCreateElement(doc, STRING_div);
950 target.id = targetId;
952 positionAbsolute(target);
953 domAppendChild(doc.body, target);
955 target = existing_target;
957 var div = domCreateElement(doc, STRING_div);
958 target.appendChild(div);
959 div.innerHTML = html;
964 * Sets the jsinstance attribute on a node according to its context.
966 * @param {Element} template The template DOM node to set the instance
969 * @param {Array} values The current input context, the array of
970 * values of which the template node will render one instance.
972 * @param {number} index The index of this template node in values.
974 function jstSetInstance(template, values, index) {
975 if (index == jsLength(values) - 1) {
976 domSetAttribute(template, ATT_instance, CHAR_asterisk + index);
978 domSetAttribute(template, ATT_instance, STRING_empty + index);
984 * Log the current state.
985 * @param {string} caller An identifier for the caller of .log_.
986 * @param {Element} template The template node being processed.
987 * @param {Object} jstAttributeValues The jst attributes of the template node.
989 JstProcessor.prototype.logState_ = function(
990 caller, template, jstAttributeValues) {
993 msg += '<caption>' + caller + '</caption>';
996 msg += '<tr><td>' + 'id:' + '</td><td>' + template.id + '</td></tr>';
999 msg += '<tr><td>' + 'name:' + '</td><td>' + template.name + '</td></tr>';
1001 if (jstAttributeValues) {
1002 msg += '<tr><td>' + 'attr:' +
1003 '</td><td>' + jsToSource(jstAttributeValues) + '</td></tr>';
1005 msg += '</tbody></table><br/>';
1006 this.logs_.push(msg);
1012 * Retrieve the processing logs.
1013 * @return {Array.<string>} The processing logs.
1015 JstProcessor.prototype.getLogs = function() {