helper.html 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>helper-demo</title>
  6. <script src="../../dist/template-native.js"></script>
  7. </head>
  8. <body>
  9. <h1>辅助方法</h1>
  10. <div id="content"></div>
  11. <script id="test" type="text/html">
  12. <%=dateFormat(time, 'yyyy<b>年</b> MM月 dd日 hh:mm:ss')%>
  13. </script>
  14. <script>
  15. /**
  16. * 对日期进行格式化,
  17. * @param date 要格式化的日期
  18. * @param format 进行格式化的模式字符串
  19. * 支持的模式字母有:
  20. * y:年,
  21. * M:年中的月份(1-12),
  22. * d:月份中的天(1-31),
  23. * h:小时(0-23),
  24. * m:分(0-59),
  25. * s:秒(0-59),
  26. * S:毫秒(0-999),
  27. * q:季度(1-4)
  28. * @return String
  29. * @author yanis.wang
  30. * @see http://yaniswang.com/frontend/2013/02/16/dateformat-performance/
  31. */
  32. template.helper('dateFormat', function (date, format) {
  33. date = new Date(date);
  34. var map = {
  35. "M": date.getMonth() + 1, //月份
  36. "d": date.getDate(), //日
  37. "h": date.getHours(), //小时
  38. "m": date.getMinutes(), //分
  39. "s": date.getSeconds(), //秒
  40. "q": Math.floor((date.getMonth() + 3) / 3), //季度
  41. "S": date.getMilliseconds() //毫秒
  42. };
  43. format = format.replace(/([yMdhmsqS])+/g, function(all, t){
  44. var v = map[t];
  45. if(v !== undefined){
  46. if(all.length > 1){
  47. v = '0' + v;
  48. v = v.substr(v.length-2);
  49. }
  50. return v;
  51. }
  52. else if(t === 'y'){
  53. return (date.getFullYear() + '').substr(4 - all.length);
  54. }
  55. return all;
  56. });
  57. return format;
  58. });
  59. // --------
  60. var data = {
  61. time: (new Date).toString(),
  62. };
  63. var html = template('test', data);
  64. document.getElementById('content').innerHTML = html;
  65. </script>
  66. </body>
  67. </html>