Koa(四):ejs模板引擎
程序员文章站
2022-07-03 09:09:38
安装npm i koa-views --savenpm i ejs --save示例// app.jsconst Koa = require('koa');const views = require('koa-views');const router = require('koa-router')();const app = new Koa();/** * 第三方中间件:配置模板引擎 * app.use(views(__dirname, { extension: 'ejs...
安装
npm i koa-views --save
npm i ejs --save
示例
// app.js
const Koa = require('koa');
const views = require('koa-views');
const router = require('koa-router')();
const app = new Koa();
/**
* 第三方中间件:配置模板引擎
* app.use(views(__dirname, { extension: 'ejs' })); // 文件扩展名必须为 .ejs 结尾
* or
* app.use(views(__dirname, { map: { html: 'ejs' } })); // 文件扩展名必须为 .html 结尾
*/
app.use(views('views', { extension: 'ejs' }));
/**
* 配置公共信息
* 路由界面均可获取
*/
app.use(async (ctx,next) => {
ctx.state = {
data:{
name: 'ProsperLee'
},
}
await next();
});
router
.get('/', async ctx => {
let htmlstr = '<p style="color: red;">ProsperLee</p>';
await ctx.render('index', { htmlstr })
})
app
.use(router.routes())
.use(router.allowedMethods())
.listen(3000);
console.log('Server run in http://localhost:3000/');
<!-- views/index.ejs -->
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h2>Hello ProsperLee</h2>
<p><%= data.name %></p>
<%- include('components/table.ejs') %>
</body>
</html>
<!-- views/components/table.ejs -->
<%- htmlstr %>
<table border="1">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td>ProsperLee</td>
<td>23</td>
<td>男</td>
</tr>
<tr>
<td>Lucy</td>
<td>20</td>
<td>女</td>
</tr>
<tr>
<td>Tom</td>
<td>16</td>
<td>男</td>
</tr>
</tbody>
</table>
本文地址:https://blog.csdn.net/weixin_43526371/article/details/108566490
上一篇: C/C++ 刷PAT过程出现的问题汇总
下一篇: 处暑这天吃啥饭菜?处暑传统饮食文化