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 JstProcessor.prototype.jstSelect_ = function(context, template, select) {
559 var value = context.jsexec(select, template);
561 // Enable reprocessing: if this template is reprocessed, then only
562 // fill the section instance here. Otherwise do the cardinal
563 // processing of a new template.
564 var instance = domGetAttribute(template, ATT_instance);
566 var instanceLast = false;
568 if (instance.charAt(0) == CHAR_asterisk) {
569 instance = parseInt10(instance.substr(1));
572 instance = parseInt10(/** @type string */(instance));
576 // The expression value instanceof Array is occasionally false for
577 // arrays, seen in Firefox. Thus we recognize an array as an object
578 // which is not null that has a length property. Notice that this
579 // also matches input data with a length property, so this property
580 // name should be avoided in input data.
581 var multiple = isArray(value);
582 var count = multiple ? jsLength(value) : 1;
583 var multipleEmpty = (multiple && count == 0);
586 value = /** @type Array */(value);
588 // For an empty array, keep the first template instance and mark
589 // it last. Remove all other template instances.
591 domSetAttribute(template, ATT_instance, STRING_asteriskzero);
592 displayNone(template);
594 domRemoveNode(template);
598 displayDefault(template);
599 // For a non empty array, create as many template instances as
600 // are needed. If the template is first processed, as many
601 // template instances are needed as there are values in the
602 // array. If the template is reprocessed, new template instances
603 // are only needed if there are more array values than template
604 // instances. Those additional instances are created by
605 // replicating the last template instance.
607 // When the template is first processed, there is no jsinstance
608 // attribute. This is indicated by instance === null, except in
609 // opera it is instance === "". Notice also that the === is
610 // essential, because 0 == "", presumably via type coercion to
612 if (instance === null || instance === STRING_empty ||
613 (instanceLast && instance < count - 1)) {
614 // A queue of calls to push.
615 var queue = me.createArray_();
617 var instancesStart = instance || 0;
619 for (i = instancesStart, I = count - 1; i < I; ++i) {
620 var node = domCloneNode(template);
621 domInsertBefore(node, template);
623 jstSetInstance(/** @type Element */(node), value, i);
624 clone = context.clone(value[i], i, count);
626 queue.push(me.jstProcessInner_, clone, node,
627 JsEvalContext.recycle, clone, null);
630 // Push the originally present template instance last to keep
631 // the order aligned with the DOM order, because the newly
632 // created template instances are inserted *before* the
633 // original instance.
634 jstSetInstance(template, value, i);
635 clone = context.clone(value[i], i, count);
636 queue.push(me.jstProcessInner_, clone, template,
637 JsEvalContext.recycle, clone, null);
639 } else if (instance < count) {
640 var v = value[instance];
642 jstSetInstance(template, value, instance);
643 var clone = context.clone(v, instance, count);
644 var queue = me.createArray_();
645 queue.push(me.jstProcessInner_, clone, template,
646 JsEvalContext.recycle, clone, null);
649 domRemoveNode(template);
654 displayNone(template);
656 displayDefault(template);
657 var clone = context.clone(value, 0, 1);
658 var queue = me.createArray_();
659 queue.push(me.jstProcessInner_, clone, template,
660 JsEvalContext.recycle, clone, null);
668 * Implements the jsvars attribute: evaluates each of the values and
669 * assigns them to variables in the current context. Similar to
670 * jsvalues, except that all values are treated as vars, independent
673 * @param {JsEvalContext} context Current evaluation context.
675 * @param {Element} template Currently processed template node.
677 * @param {Array} values Processed value of the jsvalues attribute: a
678 * flattened array of pairs. The second element in the pair is a
679 * function that can be passed to jsexec() for evaluation in the
680 * current jscontext, and the first element is the variable name that
681 * the value returned by jsexec is assigned to.
683 JstProcessor.prototype.jstVars_ = function(context, template, values) {
684 for (var i = 0, I = jsLength(values); i < I; i += 2) {
685 var label = values[i];
686 var value = context.jsexec(values[i+1], template);
687 context.setVariable(label, value);
693 * Implements the jsvalues attribute: evaluates each of the values and
694 * assigns them to variables in the current context (if the name
695 * starts with '$', javascript properties of the current template node
696 * (if the name starts with '.'), or DOM attributes of the current
697 * template node (otherwise). Since DOM attribute values are always
698 * strings, the value is coerced to string in the latter case,
699 * otherwise it's the uncoerced javascript value.
701 * @param {JsEvalContext} context Current evaluation context.
703 * @param {Element} template Currently processed template node.
705 * @param {Array} values Processed value of the jsvalues attribute: a
706 * flattened array of pairs. The second element in the pair is a
707 * function that can be passed to jsexec() for evaluation in the
708 * current jscontext, and the first element is the label that
709 * determines where the value returned by jsexec is assigned to.
711 JstProcessor.prototype.jstValues_ = function(context, template, values) {
712 for (var i = 0, I = jsLength(values); i < I; i += 2) {
713 var label = values[i];
714 var value = context.jsexec(values[i+1], template);
716 if (label.charAt(0) == CHAR_dollar) {
717 // A jsvalues entry whose name starts with $ sets a local
719 context.setVariable(label, value);
721 } else if (label.charAt(0) == CHAR_period) {
722 // A jsvalues entry whose name starts with . sets a property of
723 // the current template node. The name may have further dot
724 // separated components, which are translated into namespace
725 // objects. This specifically allows to set properties on .style
726 // using jsvalues. NOTE(mesch): Setting the style attribute has
727 // no effect in IE and hence should not be done anyway.
728 var nameSpaceLabel = label.substr(1).split(CHAR_period);
729 var nameSpaceObject = template;
730 var nameSpaceDepth = jsLength(nameSpaceLabel);
731 for (var j = 0, J = nameSpaceDepth - 1; j < J; ++j) {
732 var jLabel = nameSpaceLabel[j];
733 if (!nameSpaceObject[jLabel]) {
734 nameSpaceObject[jLabel] = {};
736 nameSpaceObject = nameSpaceObject[jLabel];
738 nameSpaceObject[nameSpaceLabel[nameSpaceDepth - 1]] = value;
741 // Any other jsvalues entry sets an attribute of the current
743 if (typeof value == TYPE_boolean) {
744 // Handle boolean values that are set as attributes specially,
745 // according to the XML/HTML convention.
747 domSetAttribute(template, label, label);
749 domRemoveAttribute(template, label);
752 domSetAttribute(template, label, STRING_empty + value);
760 * Implements the jscontent attribute. Evalutes the expression in
761 * jscontent in the current context and with the current variables,
762 * and assigns its string value to the content of the current template
765 * @param {JsEvalContext} context Current evaluation context.
767 * @param {Element} template Currently processed template node.
769 * @param {Function} content Processed value of the jscontent
772 JstProcessor.prototype.jstContent_ = function(context, template, content) {
773 // NOTE(mesch): Profiling shows that this method costs significant
774 // time. In jstemplate_perf.html, it's about 50%. I tried to replace
775 // by HTML escaping and assignment to innerHTML, but that was even
777 var value = STRING_empty + context.jsexec(content, template);
778 // Prevent flicker when refreshing a template and the value doesn't
780 if (template.innerHTML == value) {
783 while (template.firstChild) {
784 domRemoveNode(template.firstChild);
786 var t = domCreateTextNode(this.document_, value);
787 domAppendChild(template, t);
792 * Caches access to and parsing of template processing attributes. If
793 * domGetAttribute() is called every time a template attribute value
794 * is used, it takes more than 10% of the time.
796 * @param {Element} template A DOM element node of the template.
798 * @return {Object} A javascript object that has all js template
799 * processing attribute values of the node as properties.
801 JstProcessor.prototype.jstAttributes_ = function(template) {
802 if (template[PROP_jstcache]) {
803 return template[PROP_jstcache];
806 var jstid = domGetAttribute(template, ATT_jstcache);
808 return template[PROP_jstcache] = JstProcessor.jstcache_[jstid];
811 return JstProcessor.prepareNode_(template);
816 * Helps to implement the transclude attribute, and is the initial
817 * call to get hold of a template from its ID.
819 * If the ID is not present in the DOM, and opt_loadHtmlFn is specified, this
820 * function will call that function and add the result to the DOM, before
821 * returning the template.
823 * @param {string} name The ID of the HTML element used as template.
824 * @param {Function=} opt_loadHtmlFn A function which, when called, will return
825 * HTML that contains an element whose ID is 'name'.
827 * @return {Element|null} The DOM node of the template. (Only element nodes
828 * can be found by ID, hence it's a Element.)
830 function jstGetTemplate(name, opt_loadHtmlFn) {
833 if (opt_loadHtmlFn) {
834 section = jstLoadTemplateIfNotPresent(doc, name, opt_loadHtmlFn);
836 section = domGetElementById(doc, name);
839 JstProcessor.prepareTemplate_(section);
840 var ret = domCloneElement(section);
841 domRemoveAttribute(ret, STRING_id);
849 * This function is the same as 'jstGetTemplate' but, if the template
850 * does not exist, throw an exception.
852 * @param {string} name The ID of the HTML element used as template.
853 * @param {Function} opt_loadHtmlFn A function which, when called, will return
854 * HTML that contains an element whose ID is 'name'.
856 * @return {Element} The DOM node of the template. (Only element nodes
857 * can be found by ID, hence it's a Element.)
859 function jstGetTemplateOrDie(name, opt_loadHtmlFn) {
860 var x = jstGetTemplate(name, opt_loadHtmlFn);
862 throw new Error('jstGetTemplate() returned null');
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|string} 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) {