这篇教大家如何使用模板引擎
这里我们使用ejs模板引擎做 个例子,你们自己选择自己熟练的模板引擎
使用的版本:

文件夹目录结构:

1.编写index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| const Koa = require('koa') const views = require('koa-views') const path = require('path') const app = new Koa()
// 加载模板引擎 app.use(views(path.join(__dirname, './views'), { extension: 'ejs' })) app.use( async ( ctx ) => { let title = 'hello koa2' await ctx.render('index', { title, }) })
app.listen(3000, () => { console.log('localhost:3000') })
|
2.编写/views/index.ejs
1 2 3 4 5 6 7 8 9 10 11 12 13
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>index</title> </head> <body> <h2>views index</h2> <h1><%= title %></h1> </body> </html>
|
3.启动服务
4.打开浏览器

我们想要的结果就出来了
后记
本文首发于微信公众号:node前端
不妨关注一下