一、使用 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   = \"postbird\";
 await ctx.render(\'index\', {
  
 });
});

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\',{ :\'nunjucks\',food});
}); 

4、模板语法

更多的语法可以看文档:

https://mozilla.github.io/nunjucks/cn/templating.html#for

<body>
 <h1>{{ }}</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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

收藏 打印