问题描述
我试图按照文档添加带有 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';
});