koa中使用模板引擎

在node中使用模板引擎需要一个中间件koa-views

在koa中使用ejs

安装模块

# 安装koa模板使用中间件
npm install --save koa-views

# 安装ejs模板引擎
npm install --save ejs

使用模板引擎

demo源码

https://github.com/ChenShenhai/koa2-note/blob/master/demo/ejs/

文件目录

├── package.json
├── index.js
└── view
    └── index.ejs

./index.js文件

const Koa = require('koa')
const views = require('koa-views')
const path = require('path')
const app = new Koa()

// 加载模板引擎
app.use(views(path.join(__dirname, './view'), {
  extension: 'ejs'
}))

app.use( async ( ctx ) => {
  let title = 'hello koa2'
  await ctx.render('index', {
    title,
  })
})

app.listen(3000)

./view/index.ejs 模板

<!DOCTYPE html>
<html>
<head>
    <title><%= title %></title>
</head>
<body>
    <h1><%= title %></h1>
    <p>EJS Welcome to <%= title %></p>
</body>
</html>

koa-views源码地址:https://github.com/queckezz/koa-views

模板引擎

适用于 koa 的模板引擎选择非常多,比如 jadeejsnunjucksxtemplate 等。

是否支持前后端混用
jade 直接淘汰,相信在前端js领域一般不会选择 jade 来渲染。

nunjucks 也使用的比较少(ejs其实也少),更多人会选择使用 handlebars 。

xtemplate 目前在阿里的系统中前后端混用中已经得到论证,节约了模板前后端转换的时间。

参考:
https://chenshenhai.github.io/koa2-note/note/template/add.html
http://book.apebook.org/minghe/koa-action/xtemplate/xtemplate.html



转载:https://www.jianshu.com/p/be39a99c92ca

猜你喜欢

转载自blog.csdn.net/bbsyi/article/details/86477472