1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
(function (root, factory) {
'use strict';
if (typeof define === 'function' && define.amd) {
define([
'underscore'
], factory);
} else {
root.mageTemplate = factory(root._);
}
}(this, function (_) {
'use strict';
/**
* Checks if provided string is a valid DOM selector.
*
* @param {String} selector - Selector to be checked.
* @returns {Boolean}
*/
function isSelector(selector) {
try {
document.querySelector(selector);
return true;
} catch (e) {
return false;
}
}
/**
* Unescapes characters used in underscore templates.
*
* @param {String} str - String to be processed.
* @returns {String}
*/
function unescape(str) {
return str.replace(/<%|%3C%/g, '<%').replace(/%>|%%3E/g, '%>');
}
/**
* If 'tmpl' is a valid selector, returns target node's innerHTML if found.
* Else, returns empty string and emits console warning.
* If 'tmpl' is not a selector, returns 'tmpl' as is.
*
* @param {String} tmpl
* @returns {String}
*/
function getTmplString(tmpl) {
if (isSelector(tmpl)) {
tmpl = document.querySelector(tmpl);
if (tmpl) {
tmpl = tmpl.innerHTML.trim();
} else {
console.warn('No template was found by selector: ' + tmpl);
tmpl = '';
}
}
return unescape(tmpl);
}
/**
* Compiles or renders template provided either
* by selector or by the template string.
*
* @param {String} tmpl - Template string or selector.
* @param {(Object|Array|Function)} [data] - Data object with which to render template.
* @returns {String|Function}
*/
return function (tmpl, data) {
var render;
tmpl = getTmplString(tmpl);
render = _.template(tmpl);
return !_.isUndefined(data) ?
render(data) :
render;
};
}));