template.js 2.1 KB

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