[关闭]
@dlutwuwei 2015-12-15T11:06:28.000000Z 字数 596 阅读 538

tppl模板引擎开发实践

未分类


字符串拼接

  1. function tppl(tpl, data, fast) {
  2. var fn = function(d) {
  3. var i,
  4. k = [],
  5. v = [];
  6. for (i in d) {
  7. k.push(i);
  8. v.push(d[i]);
  9. }
  10. return (new Function(k, fn.$)).apply(d, v);
  11. };
  12. if (!fn.$) {
  13. fn.$ = 'var $=""\n';
  14. var tpls = tpl.replace(/[\r\t\n]/g, " ").replace(/\s+/g, ' ').split('%>'),
  15. i = 0;
  16. while (i < tpls.length) {
  17. var p = tpls[i].replace(/\'/g, "\"");
  18. var x = p.indexOf('<%');
  19. if (p[x + 2] == '=') {
  20. //<%=..%>
  21. fn.$ += "$+='" + p.substr(0, x) + "'\n";
  22. fn.$ += "$+=" + p.substr(x + 3) + "\n";
  23. } else if (x >= 0) {
  24. //<% %>
  25. fn.$ += "$+='" + p.substr(0, x) + "'\n";
  26. fn.$ += p.substr(x + 2) + "\n";
  27. } else {
  28. //html
  29. fn.$ += "$+='" + p + "'\n";
  30. }
  31. i++;
  32. }
  33. fn.$ += "return $";
  34. }
  35. return data ? fn(data) : fn;
  36. }
  37. module.exports = tppl;
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注