tmpl.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. * http://www.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 document, define, module */
  15. ;(function ($) {
  16. 'use strict'
  17. var tmpl = function (str, data) {
  18. var f = !/[^\w\-\.:]/.test(str)
  19. ? tmpl.cache[str] = tmpl.cache[str] || tmpl(tmpl.load(str))
  20. : new Function(// eslint-disable-line no-new-func
  21. tmpl.arg + ',tmpl',
  22. 'var _e=tmpl.encode' + tmpl.helper + ",_s='" +
  23. str.replace(tmpl.regexp, tmpl.func) + "';return _s;"
  24. )
  25. return data ? f(data, tmpl) : function (data) {
  26. return f(data, tmpl)
  27. }
  28. }
  29. tmpl.cache = {}
  30. tmpl.load = function (id) {
  31. return document.getElementById(id).innerHTML
  32. }
  33. tmpl.regexp = /([\s'\\])(?!(?:[^{]|\{(?!%))*%\})|(?:\{%(=|#)([\s\S]+?)%\})|(\{%)|(%\})/g
  34. tmpl.func = function (s, p1, p2, p3, p4, p5) {
  35. if (p1) { // whitespace, quote and backspace in HTML context
  36. return {
  37. '\n': '\\n',
  38. '\r': '\\r',
  39. '\t': '\\t',
  40. ' ': ' '
  41. }[p1] || '\\' + p1
  42. }
  43. if (p2) { // interpolation: {%=prop%}, or unescaped: {%#prop%}
  44. if (p2 === '=') {
  45. return "'+_e(" + p3 + ")+'"
  46. }
  47. return "'+(" + p3 + "==null?'':" + p3 + ")+'"
  48. }
  49. if (p4) { // evaluation start tag: {%
  50. return "';"
  51. }
  52. if (p5) { // evaluation end tag: %}
  53. return "_s+='"
  54. }
  55. }
  56. tmpl.encReg = /[<>&"'\x00]/g
  57. tmpl.encMap = {
  58. '<': '&lt;',
  59. '>': '&gt;',
  60. '&': '&amp;',
  61. '"': '&quot;',
  62. "'": '&#39;'
  63. }
  64. tmpl.encode = function (s) {
  65. return (s == null ? '' : '' + s).replace(
  66. tmpl.encReg,
  67. function (c) {
  68. return tmpl.encMap[c] || ''
  69. }
  70. )
  71. }
  72. tmpl.arg = 'o'
  73. tmpl.helper = ",print=function(s,e){_s+=e?(s==null?'':s):_e(s);}" +
  74. ',include=function(s,d){_s+=tmpl(s,d);}'
  75. if (typeof define === 'function' && define.amd) {
  76. define(function () {
  77. return tmpl
  78. })
  79. } else if (typeof module === 'object' && module.exports) {
  80. module.exports = tmpl
  81. } else {
  82. $.tmpl = tmpl
  83. }
  84. }(this))