如何使用 express 为自定义过滤器配置 nunjucks?
how to configure nunjucks for custom filters with express?
我试图按照文档添加带有 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';
});
我试图按照文档添加带有 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';
});