Nunjucks在Koa中的应用
- app.js
const koa = require('koa');
const app = new koa();
const router = require('./router')
const nunjucks = require('koa-nunjuncks-2');
app.use(nunjucks({
ext: 'html', // 指定视图文件默认后缀
path: path.join(__dirname, 'views'), // 指定视图目录
nunjucksConfig:{
trimBlocks: true // 开启转义,防止XSS
}
}))
注: 配置要在router前面
- 使用 (ctx.render(path))
- /controller/home.js
user: async (ctx, next) =>{
await ctx.render('home/login',{
btnName: 'GoGoGo'
})
}
关键代码
- 使用&&挂载&&配置nunjucks
const nunjucks = require('koa-nunjucks-2');
app.use(nunjucks({
ext: 'html', // 默认的后缀名
path: path.join(__dirname, 'views'),
nunjucksConfig:{
trimBlocks: true // 开启转义,防止XSS
}
}));
- views的目录结构如下
- 例如使用 /views/home/login.html 模板进行渲染
async (ctx, next) =>{
awaite ctx.render('home/login',{
btnName