如何使用 express 为自定义过滤器配置 nunjucks?

问题描述

我试图按照文档添加带有 nunjucks 的自定义过滤器。但是运行代码显示输出 -- Error: filter not found: my_filter_here

这些是我的配置:

index.js

const express = require('express');
const nunjucks = require('nunjucks');

const port = 3000;
const app = express();

nunjucks.configure('views',{
  autoescape: true,express: app
})

app.set('view engine','html');

const env = new nunjucks.Environment();

env.addFilter('is_undefined',function(obj) {
  return typeof obj === 'undefined';
});

对于渲染模板,我正在使用

res.render('register.html',{errors: errors});

在我的模板中,我是这样设置的:

{% if errors|is_undefined %}
  // do something
{% endif %}

这是我得到的错误错误filter not found: is_undefined

我在发布这个问题之前搜索过 s.o,一些答案表明我需要使用 env.render(),我之前添加了过滤器,而不是 res.render。当我将其更改为这样时,它不会呈现我的 html 页面。有什么办法可以解决问题吗?

提前致谢。 :)

解决方法

根据文档:configure returns an Environment instance。因此

const env = nunjucks.configure('views',{
  autoescape: true,express: app
})

env.addFilter('is_undefined',function(obj) {
  return typeof obj === 'undefined';
});

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...