1-1 安装依赖

  1. cnpm i egg-view-nunjucks -S
  2. //-S --save

1-2、config/plugin.js

module.exports = {
  nunjucks: {
    enable: true,
    package: 'egg-view-nunjucks',
  }
};

1-3、配置config/config.default.js

config.view = {
    defaultViewEngine: 'nunjucks',
    mapping: {
      '.html': 'nunjucks',
    },
};

1-4 app/view

在app目录下,新建view文件夹,放置html页面

1-5 在controller中使用

home.js

class HomeController extends Controller {
  async index() {
    const { ctx } = this;
    await ctx.render("home",{arr:["html","css","js"],isShow:false})
  }
}

html

<body>
    {% for item in arr %}
    <p>{{item}}</p>
    {% endfor %}

    {% if isShow %}
    <p>show</p>
    {% endif %}
</body>