template.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /* !
  2. * template.js v0.7.1 (https://github.com/yanhaijing/template.js)
  3. * API https://github.com/yanhaijing/template.js/blob/master/doc/api.md
  4. * Copyright 2015 yanhaijing. All Rights Reserved
  5. * Licensed under MIT (https://github.com/yanhaijing/template.js/blob/master/MIT-LICENSE.txt)
  6. */
  7. /* eslint-disable */
  8. ;(function(root, factory) {
  9. var template = factory(root);
  10. if (typeof define === 'function' && define.amd) {
  11. // AMD
  12. define('template', function() {
  13. return template;
  14. });
  15. } else if (typeof exports === 'object') {
  16. // Node.js
  17. module.exports = template;
  18. } else {
  19. // Browser globals
  20. var _template = root.template;
  21. template.noConflict = function() {
  22. if (root.template === template) {
  23. root.template = _template;
  24. }
  25. return template;
  26. };
  27. root.template = template;
  28. }
  29. }(this, function(root) {
  30. 'use strict';
  31. var o = {
  32. sTag: '<%',//开始标签
  33. eTag: '%>',//结束标签
  34. compress: false,//是否压缩html
  35. escape: true, //默认输出是否进行HTML转义
  36. error: function (e) {}//错误回调
  37. };
  38. var functionMap = {}; //内部函数对象
  39. //修饰器前缀
  40. var modifierMap = {
  41. '': function (param) {return nothing(param)},
  42. 'h': function (param) {return encodeHTML(param)},
  43. 'u': function (param) {return encodeURI(param)}
  44. };
  45. var toString = {}.toString;
  46. var slice = [].slice;
  47. function type(x) {
  48. if(x === null){
  49. return 'null';
  50. }
  51. var t= typeof x;
  52. if(t !== 'object'){
  53. return t;
  54. }
  55. var c = toString.call(x).slice(8, -1).toLowerCase();
  56. if(c !== 'object'){
  57. return c;
  58. }
  59. if(x.constructor==Object){
  60. return c;
  61. }
  62. return 'unknown';
  63. }
  64. function isObject(obj) {
  65. return type(obj) === 'object';
  66. }
  67. function isFunction(fn) {
  68. return type(fn) === 'function';
  69. }
  70. function isString(str) {
  71. return type(str) === 'string';
  72. }
  73. function extend() {
  74. var target = arguments[0] || {};
  75. var arrs = slice.call(arguments, 1);
  76. var len = arrs.length;
  77. for (var i = 0; i < len; i++) {
  78. var arr = arrs[i];
  79. for (var name in arr) {
  80. target[name] = arr[name];
  81. }
  82. }
  83. return target;
  84. }
  85. function clone() {
  86. var args = slice.call(arguments);
  87. return extend.apply(null, [{}].concat(args));
  88. }
  89. function nothing(param) {
  90. return param;
  91. }
  92. function encodeHTML(source) {
  93. return String(source)
  94. .replace(/&/g,'&amp;')
  95. .replace(/</g,'&lt;')
  96. .replace(/>/g,'&gt;')
  97. .replace(/\\/g,'&#92;')
  98. .replace(/"/g,'&quot;')
  99. .replace(/'/g,'&#39;');
  100. }
  101. function compress(html) {
  102. return html.replace(/\s+/g, ' ').replace(/<!--[\w\W]*?-->/g, '');
  103. }
  104. function consoleAdapter(cmd, msg) {
  105. typeof console !== 'undefined' && console[cmd] && console[cmd](msg);
  106. }
  107. function handelError(e) {
  108. var message = 'template.js error\n\n';
  109. for (var key in e) {
  110. message += '<' + key + '>\n' + e[key] + '\n\n';
  111. }
  112. message += '<message>\n' + e.message + '\n\n';
  113. consoleAdapter('error', message);
  114. o.error(e);
  115. function error() {
  116. return 'template.js error';
  117. }
  118. error.toString = function () {
  119. return '__code__ = "template.js error"';
  120. }
  121. return error;
  122. }
  123. function parse(tpl, opt) {
  124. var code = '';
  125. var sTag = opt.sTag;
  126. var eTag = opt.eTag;
  127. var escape = opt.escape;
  128. function parsehtml(line) {
  129. // 单双引号转义,换行符替换为空格
  130. line = line.replace(/('|")/g, '\\$1');
  131. var lineList = line.split('\n');
  132. var code = '';
  133. for (var i = 0; i < lineList.length; i++) {
  134. code += ';__code__ += ("' + lineList[i] + (i === lineList.length - 1 ? '")\n' : '\\n")\n');
  135. }
  136. return code;
  137. }
  138. function parsejs(line) {
  139. //var reg = /^(:?)(.*?)=(.*)$/;
  140. var reg = /^(?:=|(:.*?)=)(.*)$/
  141. var html;
  142. var arr;
  143. var modifier;
  144. // = := :*=
  145. // :h=123 [':h=123', 'h', '123']
  146. if (arr = reg.exec(line)) {
  147. html = arr[2]; // 输出
  148. if (Boolean(arr[1])) {
  149. // :开头
  150. modifier = arr[1].slice(1);
  151. } else {
  152. // = 开头
  153. modifier = escape ? 'h' : '';
  154. }
  155. return ';__code__ += __modifierMap__["' + modifier + '"](typeof (' + html + ') !== "undefined" ? (' + html + ') : "")\n';
  156. }
  157. //原生js
  158. return ';' + line + '\n';
  159. }
  160. var tokens = tpl.split(sTag);
  161. for (var i = 0, len = tokens.length; i < len; i++) {
  162. var token = tokens[i].split(eTag);
  163. if (token.length === 1) {
  164. code += parsehtml(token[0]);
  165. } else {
  166. code += parsejs(token[0], true);
  167. if (token[1]) {
  168. code += parsehtml(token[1]);
  169. }
  170. }
  171. }
  172. return code;
  173. }
  174. function compiler(tpl, opt) {
  175. var mainCode = parse(tpl, opt);
  176. var headerCode = '\n' +
  177. ' var html = (function (__data__, __modifierMap__) {\n' +
  178. ' var __str__ = "", __code__ = "";\n' +
  179. ' for(var key in __data__) {\n' +
  180. ' __str__+=("var " + key + "=__data__[\'" + key + "\'];");\n' +
  181. ' }\n' +
  182. ' eval(__str__);\n\n';
  183. var footerCode = '\n' +
  184. ' ;return __code__;\n' +
  185. ' }(__data__, __modifierMap__));\n' +
  186. ' return html;\n';
  187. var code = headerCode + mainCode + footerCode;
  188. code = code.replace(/[\r]/g, ' '); // ie 7 8 会报错,不知道为什么
  189. try {
  190. var Render = new Function('__data__', '__modifierMap__', code);
  191. Render.toString = function () {
  192. return mainCode;
  193. }
  194. return Render;
  195. } catch(e) {
  196. e.temp = 'function anonymous(__data__, __modifierMap__) {' + code + '}';
  197. throw e;
  198. }
  199. }
  200. function compile(tpl, opt) {
  201. opt = clone(o, opt);
  202. try {
  203. var Render = compiler(tpl, opt);
  204. } catch(e) {
  205. e.name = 'CompileError';
  206. e.tpl = tpl;
  207. e.render = e.temp;
  208. delete e.temp;
  209. return handelError(e);
  210. }
  211. function render(data) {
  212. data = clone(functionMap, data);
  213. try {
  214. var html = Render(data, modifierMap);
  215. html = opt.compress ? compress(html) : html;
  216. return html;
  217. } catch(e) {
  218. e.name = 'RenderError';
  219. e.tpl = tpl;
  220. e.render = Render.toString();
  221. return handelError(e)();
  222. }
  223. }
  224. render.toString = function () {
  225. return Render.toString();
  226. };
  227. return render;
  228. }
  229. function template(tpl, data) {
  230. if (typeof tpl !== 'string') {
  231. return '';
  232. }
  233. var fn = compile(tpl);
  234. if (!isObject(data)) {
  235. return fn;
  236. }
  237. return fn(data);
  238. }
  239. template.config = function (option) {
  240. if (isObject(option)) {
  241. o = extend(o, option);
  242. }
  243. return clone(o);
  244. };
  245. template.registerFunction = function(name, fn) {
  246. if (!isString(name)) {
  247. return clone(functionMap);
  248. }
  249. if (!isFunction(fn)) {
  250. return functionMap[name];
  251. }
  252. return functionMap[name] = fn;
  253. }
  254. template.unregisterFunction = function (name) {
  255. if (!isString(name)) {
  256. return false;
  257. }
  258. delete functionMap[name];
  259. return true;
  260. }
  261. template.registerModifier = function(name, fn) {
  262. if (!isString(name)) {
  263. return clone(modifierMap);
  264. }
  265. if (!isFunction(fn)) {
  266. return modifierMap[name];
  267. }
  268. return modifierMap[name] = fn;
  269. }
  270. template.unregisterModifier = function (name) {
  271. if (!isString(name)) {
  272. return false;
  273. }
  274. delete modifierMap[name];
  275. return true;
  276. }
  277. template.__encodeHTML = encodeHTML;
  278. template.__compress = compress;
  279. template.__handelError = handelError;
  280. template.__compile = compile;
  281. template.version = '0.7.1';
  282. return template;
  283. }));