1、安装模版

  1. cnpm i egg-view-nunjucks -S

2、配置config/plugin.js

  1. module.exports = {
  2. // had enabled by egg
  3. nunjucks : {
  4. enable: true,
  5. package: 'egg-view-nunjucks'
  6. }
  7. };

3、配置config/config.default.js

  1. // start 配置art
  2. config.view = {
  3. defaultViewEngine: 'nunjucks',
  4. mapping: {
  5. '.html': 'nunjucks',
  6. },
  7. };
  8. // end atr

4、在app下新建一个view的文件夹

  1. view文件夹里放置.html文件

5、在controller中使用render

  1. const Controller = require('egg').Controller;
  2. class HomeController extends Controller {
  3. async index() {
  4. const { ctx } = this;
  5. await ctx.render("home")
  6. }
  7. }
  8. module.exports = HomeController;

6、模版语法

  1. for:
  2. {% for item in Array %}
  3. <p>{{item}}</p>
  4. {% endfor %}
  5. if:
  6. {% if Boolean %}
  7. <p>show</p>
  8. {% endif %}