官方文档地址:https://eggjs.org/zh-cn/core/view.html
1.首先安装view 插件
npm i egg-view-nunjucks --save
2.启用插件
// config/plugin.js
module.exports = {
//...其它配置
nunjucks: {
enable: true,
package: 'egg-view-nunjucks',
},
};
3.配置插件
//config/config.default.js
const path = require('path');
module.exports = appInfo => {
const config = exports = {};
//...其它配置
//模板配置
config.view = {
defaultViewEngine: 'nunjucks',
mapping: {
'.html': 'nunjucks'
}
};
//静态资源配置
config.static = {
prefix: '/',
dir: path.join(appInfo.baseDir, 'app/public'),
};
return {
...config,
};
};
4.配置路由
//router.js
router.get('/login', controller.public.login);
5.controller控制器配置
在controller文件夹新增一个public.js
//controller/public.js
'use strict';
const Controller = require('egg').Controller;
class PublicController extends Controller {
async login() {
let title = "登录页",
footer = "Copyright © XXXXXXX",
name = "XXX后台管理系统";
await this.ctx.render('login',{
title,
footer,
name
});
}
}
module.exports = PublicController;
然后再app/view
文件夹里面新增 login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no,initial-scale=1">
<title>{{title}}</title>
<link rel="stylesheet" type="text/css" href="/css/base.css"/>
<link rel="stylesheet" type="text/css" href="/css/style.css"/>
<link href="/images/ico.ico" type="image/x-icon" rel="shortcut icon"/>
</head>
<body class="login-wrap">
<div class="login-form">
<div class="head">
<h1>{{name}}</h1>
<i></i><i></i><i></i>
</div>
<div class="avtar"></div>
<input type="text" id="username" placeholder="用户名" />
<div class="key"><input type="password" id="password" placeholder="密码" /></div>
<button type="button" id="submit">登 录</button>
</div>
<footer>{{footer}}</footer>
<script type="text/javascript" src="/javascripts/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="/javascripts/common.js"></script>
<script type="text/javascript" src="/javascripts/login.js"></script>
</body>
</html>
常用模板语法可自行百度
ps:github https://github.com/eggjs/egg-static上提供的静态资源配置,缓存超级严重。