koa模板引擎使用
//1,安装koa
npm install koa --save
// 2,安装koa-views
npm install --save koa-views
// 3,安装 ejs
npm install ejs --save
服务运行代码
const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()
const views = require('koa-views')
app.use(views('html', {
extension: 'ejs'
}))
router.get('/', async (ctx) => {
const title = '你好,ejs'
await ctx.render('index',{
title
})
}).get('/news', async (ctx) => {
const list = [12,23,45]
await ctx.render('news',{
list
})
})
app.use(router.routes())
.use(router.allowedMethods())
app.listen(30001)
模板代码index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
这是一个ejs的模板引擎
<h2><%=title%></h2>
</body>
</html>
news.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
这是新闻界面
<ul>
<%for(let i=0;i<list.length;i++){%>
<li><%=list[i]%></li>
<%}%>
</ul>
</body>
</html>
结果展示