模板

模板文件约定位于 app/view 下, 下面以nunjucks作为示例

nunjucks

首先安装模板引擎 nunjucks

$ yarn add egg-view-nunjucks

开启模板配置

config/plugin.js

exports.nunjucks = {
  enable: true,
  package: 'egg-view-nunjucks',
};

config/config.default.js

exports.view = {
  defaultViewEngine: 'nunjucks',
  mapping: {
    '.tpl': 'nunjucks',
  },
};

编写模板文件

app/view/news/list.tpl

<html>
  <head>
    <title>Hacker News</title>
    <link rel="stylesheet" href="/public/css/news.css" />
  </head>
  <body>
    <ul class="news-view view">
      {% for item in list %}
        <li class="item">
          <a href="{{ item.url }}">{{ item.title }}</a>
        </li>
      {% endfor %}
    </ul>
  </body>
</html>

编写控制器

app/controller/news.js

'use strict';
const Controller = require('egg').Controller;
class NewsController extends Controller {
  async list() {
    const dataList = {
      list: [
        { id: 1, title: 'this is news 1', url: '/news/1' },
        { id: 2, title: 'this is news 2', url: '/news/2' },
      ],
    };
    await this.ctx.render('news/list.tpl', dataList);
  }
}
module.exports = NewsController;

添加路由

module.exports = app => {
  const { router, controller } = app;
  router.get('/news', controller.news.list);
};

浏览器输入 http://localhost:7001/news 即可看到效果

MIT Licensed | Copyright © 2018-present 滇ICP备16006294号

Design by Quanzaiyu | Power by VuePress