tmpl.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. /*
  2. * JavaScript Templates
  3. * https://github.com/blueimp/JavaScript-Templates
  4. *
  5. * Copyright 2011, Sebastian Tschan
  6. * https://blueimp.net
  7. *
  8. * Licensed under the MIT license:
  9. * https://opensource.org/licenses/MIT
  10. *
  11. * Inspired by John Resig's JavaScript Micro-Templating:
  12. * http://ejohn.org/blog/javascript-micro-templating/
  13. */
  14. /* global define */
  15. /* eslint-disable strict */
  16. ;(function($) {
  17. 'use strict'
  18. var tmpl = function(str, data) {
  19. var f = !/[^\w\-.:]/.test(str)
  20. ? (tmpl.cache[str] = tmpl.cache[str] || tmpl(tmpl.load(str)))
  21. : new Function( // eslint-disable-line no-new-func
  22. tmpl.arg + ',tmpl',
  23. 'var _e=tmpl.encode' +
  24. tmpl.helper +
  25. ",_s='" +
  26. str.replace(tmpl.regexp, tmpl.func) +
  27. "';return _s;"
  28. )
  29. return data
  30. ? f(data, tmpl)
  31. : function(data) {
  32. return f(data, tmpl)
  33. }
  34. }
  35. tmpl.cache = {}
  36. tmpl.load = function(id) {
  37. return document.getElementById(id).innerHTML
  38. }
  39. tmpl.regexp = /([\s'\\])(?!(?:[^{]|\{(?!%))*%\})|(?:\{%(=|#)([\s\S]+?)%\})|(\{%)|(%\})/g
  40. tmpl.func = function(s, p1, p2, p3, p4, p5) {
  41. if (p1) {
  42. // whitespace, quote and backspace in HTML context
  43. return (
  44. {
  45. '\n': '\\n',
  46. '\r': '\\r',
  47. '\t': '\\t',
  48. ' ': ' '
  49. }[p1] || '\\' + p1
  50. )
  51. }
  52. if (p2) {
  53. // interpolation: {%=prop%}, or unescaped: {%#prop%}
  54. if (p2 === '=') {
  55. return "'+_e(" + p3 + ")+'"
  56. }
  57. return "'+(" + p3 + "==null?'':" + p3 + ")+'"
  58. }
  59. if (p4) {
  60. // evaluation start tag: {%
  61. return "';"
  62. }
  63. if (p5) {
  64. // evaluation end tag: %}
  65. return "_s+='"
  66. }
  67. }
  68. tmpl.encReg = /[<>&"'\x00]/g // eslint-disable-line no-control-regex
  69. tmpl.encMap = {
  70. '<': '&lt;',
  71. '>': '&gt;',
  72. '&': '&amp;',
  73. '"': '&quot;',
  74. "'": '&#39;'
  75. }
  76. tmpl.encode = function(s) {
  77. // eslint-disable-next-line eqeqeq
  78. return (s == null ? '' : '' + s).replace(tmpl.encReg, function(c) {
  79. return tmpl.encMap[c] || ''
  80. })
  81. }
  82. tmpl.arg = 'o'
  83. tmpl.helper =
  84. ",print=function(s,e){_s+=e?(s==null?'':s):_e(s);}" +
  85. ',include=function(s,d){_s+=tmpl(s,d);}'
  86. if (typeof define === 'function' && define.amd) {
  87. define(function() {
  88. return tmpl
  89. })
  90. } else if (typeof module === 'object' && module.exports) {
  91. module.exports = tmpl
  92. } else {
  93. $.tmpl = tmpl
  94. }
  95. })(this)