EggJs框架日记(三):插件使用(1)-模板渲染

  • 2021年5月18日
  • 技术

Egg的插件让接入应用更便捷,十分迅速,更加轻量化,好理解。

绝大多数情况,我们都需要读取数据后渲染模板,然后呈现给用户。故我们需要引入对应的模板引擎。

首先,引入插件:

npm i egg-view-nunjucks --save

接着,在config配置插件:

// config/plugin.js
import { EggPlugin } from 'egg';

const plugin: EggPlugin = {
  nunjucks: {
    enable: true,
    package: 'egg-view-nunjucks',
  },
};

export default plugin;
// config/config.default.ts
const bizConfig = {
    view: {
        defaultViewEngine: 'nunjucks',
        mapping: {
            '.html': 'nunjucks', // 左边填写后缀,表示会自动渲染.html文件
        },
    },
};

然后,编写控制器和模板文件:

// app/controller/index.ts
import { Controller } from 'egg';

export default class IndexController extends Controller {
    /**
     * 首页
     */
    public async index() {
        const {ctx} = this;
        await ctx.render('index.html');
    }

}
// app/view/index.html
<!DOCTYPE html>
<html>
<head>
    <title>首页</title>
</head>
<body>
    <h1>hello,world!</h1>
</body>
</html>

最后,添加路由:

// app/router.ts
router.get('/', controller.index.index);

这样view模板渲染简单的安装使用完成,更加详细的使用官方文档有,这里更多的将插件接入和基本使用。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注