1 // Copyright (c) 2010 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
6 * NOTE: The use of this file is deprecated. Use i18n_template2.js instead.
8 * @fileoverview This is a simple template engine inspired by JsTemplates
11 * It currently supports two handlers:
13 * * i18n-content which sets the textContent of the element
15 * <span i18n-content="myContent"></span>
16 * i18nTemplate.process(element, {'myContent': 'Content'});
18 * * i18n-values is a list of attribute-value or property-value pairs.
19 * Properties are prefixed with a '.' and can contain nested properties.
21 * <span i18n-values="title:myTitle;.style.fontSize:fontSize"></span>
22 * i18nTemplate.process(element, {
28 var i18nTemplate = (function() {
30 * This provides the handlers for the templating engine. The key is used as
31 * the attribute name and the value is the function that gets called for every
32 * single node that has this attribute.
37 * This handler sets the textContent of the element.
39 'i18n-content': function(element, attributeValue, obj) {
40 element.textContent = obj[attributeValue];
44 * This handler adds options to a select element.
46 'i18n-options': function(element, attributeValue, obj) {
47 var options = obj[attributeValue];
48 options.forEach(function(values) {
49 var option = typeof values == 'string' ? new Option(values) :
50 new Option(values[1], values[0]);
51 element.appendChild(option);
56 * This is used to set HTML attributes and DOM properties,. The syntax is:
59 * .nested.dom.property:key
61 'i18n-values': function(element, attributeValue, obj) {
62 var parts = attributeValue.replace(/\s/g, '').split(/;/);
63 for (var j = 0; j < parts.length; j++) {
64 var a = parts[j].match(/^([^:]+):(.+)$/);
69 // Ignore missing properties
70 if (propExpr in obj) {
71 var value = obj[propExpr];
72 if (propName.charAt(0) == '.') {
73 var path = propName.slice(1).split('.');
75 while (object && path.length > 1) {
76 object = object[path.shift()];
80 // In case we set innerHTML (ignoring others) we need to
81 // recursively check the content
82 if (path == 'innerHTML') {
83 process(element, obj);
87 element.setAttribute(propName, value);
90 console.warn('i18n-values: Missing value for "' + propExpr + '"');
97 var attributeNames = [];
98 for (var key in handlers) {
99 attributeNames.push(key);
101 var selector = '[' + attributeNames.join('],[') + ']';
104 * Processes a DOM tree with the {@code obj} map.
106 function process(node, obj) {
107 var elements = node.querySelectorAll(selector);
108 for (var element, i = 0; element = elements[i]; i++) {
109 for (var j = 0; j < attributeNames.length; j++) {
110 var name = attributeNames[j];
111 var att = element.getAttribute(name);
113 handlers[name](element, att, obj);