egg 框架扩展

文档:https://eggjs.org/zh-cn/basics/extend.html


demo:

比如格式日期:

在app/extend/helper.js 写入

//扩展里面引入第三方模块

/*
https://www.npmjs.com/package/silly-datetime

1.npm i silly-datetime --save


2、var sd = require('silly-datetime');
*/

var sd = require('silly-datetime');

module.exports = {
    formatTime(param) {
      // this 是 helper 对象,在其中可以调用其他 helper 方法

      // this.ctx => context 对象
      // this.app => application 对象
     
      
    //   console.log(new Date(param));


      //格式化日期  param(时间戳)

      return sd.format(new Date(param*1000), 'YYYY-MM-DD HH:mm');


    },
    getHelperData(){

        return '我是helper里面的数据'
    }
  };

调用:

//调用extend里面扩展的helper的方法
 console.log(this.ctx.helper.getHelperData());

view中

   <ul>

        <%for(var i=0;i<list.length;i++){%>
        <li><a href="/newscontent?aid=<%=list[i].aid%>"><%=list[i].title%></a>   <span>---<%=helper.formatTime(list[i].dateline)%></span></span></li>

        <%}%>
    </ul>

 

posted on 2020-05-26 13:48  LoaderMan  阅读(549)  评论(0编辑  收藏  举报

导航