一、使用 ejs 作為模板引擎
koa2 如果使用 ejs、jade 這種作為模板引擎的話,直接使用 koa-views 進行模板加載即可。
比如使用 ejs :
安裝:
yarn add koa-views ejs
使用:
在使用 render 的時候,需要進行異步文件模板讀取,因此 ctx.render 需要使用 await
const app= require('koa')();const koaViews= require('koa-views');const path = require('path');app.use(koaViews(path.join(__dirname, './view'), { extension: 'ejs'}));app.use( async ( ctx ) => { const title = "postbird"; await ctx.render('index', { title });});app.listen(3000)二、使用 nunjucks 作為模板引擎
我實在是討厭 ejs 的模板引擎語法,覺得太弱也太麻煩,而且新版本中,去除了模板繼承,很不方便。
我比較喜歡 nunjucks ,另外我發現了一個 aui-template 的模板引擎,語法使用起來很舒服,速度也很快,可以體驗一下。
aui-template 文檔地址:
http://aui.github.io/art-template/zh-cn/docs/
1、安裝 koa-nunjucks-2
使用 nunjucks 作為模板引擎,不需要安裝 koa-views。
并且可以借助別人封裝好的中間件 koa-nunjucks-2 來實現,koa-nunjucks 這個名字已經被使用,但是作為很爛,也沒維護。
有時間我會看看他的源碼,怎么加載的 nunjucks
yarn add koa-nunjucks-2
2、使用 nunjucks
const koaNunjucks = require('koa-nunjucks-2');app.use(koaNunjucks({ ext: 'njk', path: path.join(__dirname, './views'), nunjucksConfig: { trimBlocks: true }}));3、渲染模板
同樣,異步文件讀取,需要使用 await 。
router.get('view', async (ctx) => { var food = { 'ketchup': '5 tbsp', 'mustard': '1 tbsp', 'pickle': '0 tbsp' }; await ctx.render('index',{title:'nunjucks',food});}); 4、模板語法
更多的語法可以看文檔:
https://mozilla.github.io/nunjucks/cn/templating.html#for
<body> <h1>{{title}}</h1> <p>循環:</p> <ul> {% for key,value in food %} <li>{{key}} - {{value}}</li> {%endfor%} </ul></body>三、效果

四、問題
在使用 koa-nunjucks-2 的時候,發現一個問題:
app.use(nunjucks({})) 必須放在 app.use(router.routes()).use(router.allowedMethods()) 前面才能起作用,否則會報錯 ctx.render() 不是一個 function。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答