【问题标题】:how to configure nunjucks for custom filters with express?如何使用 express 为自定义过滤器配置 nunjucks?
【发布时间】:2021-03-19 13:49:55
【问题描述】:

我试图在文档之后添加一个带有 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 页面时如何。有什么解决方案可以解决问题吗?

提前致谢。 :)

【问题讨论】:

    标签: javascript express nunjucks


    【解决方案1】:

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

    const env = nunjucks.configure('views', {
      autoescape: true,
      express: app
    })
    
    env.addFilter('is_undefined', function(obj) {
      return typeof obj === 'undefined';
    });
    

    【讨论】:

    • 非常感谢!我不能投票,因为我的积分较少。我可以问更多问题吗?我需要添加const env = new nunjucks.Environment 吗?
    • 您不需要new nunjucks.Environment,因为nunjucks.configure 已经这样做了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2014-03-05
    • 1970-01-01
    • 2018-05-06
    • 1970-01-01
    相关资源
    最近更新 更多