runtime.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. function template(content) {
  2. return compile(content);
  3. };
  4. var String = this.String;
  5. function toString(value, type) {
  6. if (typeof value !== 'string') {
  7. type = typeof value;
  8. if (type === 'number') {
  9. value += '';
  10. } else if (type === 'function') {
  11. value = toString(value.call(value));
  12. } else {
  13. value = '';
  14. }
  15. }
  16. return value;
  17. };
  18. var escapeMap = {
  19. "<": "&#60;",
  20. ">": "&#62;",
  21. '"': "&#34;",
  22. "'": "&#39;",
  23. "&": "&#38;"
  24. };
  25. function escapeFn(s) {
  26. return escapeMap[s];
  27. }
  28. function escapeHTML(content) {
  29. return toString(content)
  30. .replace(/&(?![\w#]+;)|[<>"']/g, escapeFn);
  31. };
  32. var isArray = Array.isArray || function (obj) {
  33. return ({}).toString.call(obj) === '[object Array]';
  34. };
  35. function each(data, callback) {
  36. if (isArray(data)) {
  37. for (var i = 0, len = data.length; i < len; i++) {
  38. callback.call(data, data[i], i, data);
  39. }
  40. } else {
  41. for (i in data) {
  42. callback.call(data, data[i], i);
  43. }
  44. }
  45. };
  46. var utils = template.utils = {
  47. $helpers: {},
  48. $include: function () {
  49. throw new Error('art-template/loader: not support `include`.');
  50. },
  51. $string: toString,
  52. $escape: escapeHTML,
  53. $each: each
  54. };
  55. var helpers = template.helpers = utils.$helpers;
  56. function compile(fn) {
  57. var render = function (data) {
  58. try {
  59. return new fn(data) + '';
  60. } catch (e) {
  61. return showDebugInfo(e)();
  62. }
  63. };
  64. render.prototype = fn.prototype = utils;
  65. render.toString = function () {
  66. return fn + '';
  67. };
  68. return render;
  69. };
  70. function showDebugInfo(e) {
  71. var type = "{Template Error}";
  72. var message = e.stack || '';
  73. if (message) {
  74. // 利用报错堆栈信息
  75. message = message.split('\n').slice(0, 2).join('\n');
  76. } else {
  77. // 调试版本,直接给出模板语句行
  78. for (var name in e) {
  79. message += "<" + name + ">\n" + e[name] + "\n\n";
  80. }
  81. }
  82. return function () {
  83. if (typeof console === "object") {
  84. console.error(type + "\n\n" + message);
  85. }
  86. return type;
  87. };
  88. };
  89. template.helper = function (name, helper) {
  90. helpers[name] = helper;
  91. };
  92. module.exports = template;