这是ejs在githup上的项目,可以通过它进行了解
https://github.com/tj/ejs
使用 npm来安装ejs模块依赖
npm install ejs –save
ejs可以用来传参,下图中用到的module.exports = 代码
是ES6中的语法
<%= 参数名 %> 是ejs的语法
module.exports = `
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Koa Server HTML</title>
<link href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-8">
<h1>Hi <%= you %></h1>
<h2>Hello <%= me %>
</div>
<div class="col-md-4">
<p>Koa静态页面</p>
</div>
</div>
</div>
</body>
</html>
`
server/tpl/index.js
pugTpl: 这句代码跟本次笔记无关
module.exports = {
htmlTpl: require('./html'),
ejsTpl: require('./ejs'),
pugTpl: require('./pug')
}
pugTpl 跟本次笔记无关
server/index.js
const Koa = require('koa')
const app = new Koa()
const {htmlTpl, ejsTpl, pugTpl} = require('./tpl')
const ejs = require('ejs')
// const pug = require('pug')
app.use(async (ctx, next) => {
ctx.type = 'text/html; charset=utf-8'
ctx.body = ejs.render(ejsTpl, {
you: 'chenpeilun',
me: 'shenyuwan'
})
})
app.listen(5566)
在ctx.body = ejs.render(pugTpl, {
you: ‘chenpeilun’,
me: ‘shenyuwan’
})
这跟的就是ejs中的render方法,将you,me这两个参数赋值并传给ejsTpl模块
然后在网站中输入localhost:5566就可以显示模板页面