1.安装 ejs
yarn add egg-view-ejs
2.修改配置
config/plugin.js
'use strict';
exports.ejs = {
enable: true,
package: 'egg-view-ejs'
};
config/config.default.js
config.view = {
mapping: {
'.html': 'ejs'
}
};
3.创建 html 文件
app/view/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
</head>
<body>
<h1>这是首页内容</h1>
<p>id:<%=res.id%></p>
<p>name:<%=res.name%></p>
<ul>
<%for(var i=0; i<lists.length; i++) {%>
<li><%=lists[i]%></li>
<%}%>
</ul>
</body>
</html>
4.传值
app/controller/home.js
'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {
async index() {
const { ctx } = this;
const res = await ctx.service.product.index();
// ctx.body = res;
await ctx.render('index.html', {
res,
lists: ['a', 'b', 'c']
});
}
}
module.exports = HomeController;
5.效果
