如何将 Nunjucks addfilter 函数放入 Express.js 文件而不是 app.js?

How to put Nunjucks addfilter functions in Express.js file other than app.js?

我正在 express app.js 文件中初始化 nunjucks,并在同一个文件中注册自定义 addfilter 函数就好了:

  // get needed packages
const nunjucks = require('nunjucks');

  // config view engine
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');

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

  // register custom helper
env.addFilter('shorten', function(str, count) {
  return str.slice(0, count || 5);
});

但是,我还有很多 addfilter 函数要添加,但我不想将它们放入我的 app.js 文件中。具体来说,我想把它们放在这里:

node-project/views/helpers/nunjucks_helpers.js

配置此包以在所述其他文件中注册像这样的自定义过滤器的节点快速方式是什么?

最少的代码更改

在nunjucks_helpers.js中创建一个将env作为参数并导出的函数:

// helpers/nunjucks_helpers.js
function addNunjucksFilters(nunjucksEnvironment) {
  nunjucksEnvironment.addFilter(...);
  // Add all your other calls to addFilter here
}

module.exports = addNunjucksFilters;

然后导入到app.js中调用:

// app.js
var addNunjucksFilters = require('./helpers/nunjucks_helpers.js'); // Path might be different - depends on where you put app.js
// ... your existing code
addNunjucksFilters(env);

有关包含来自其他文件的函数的更多信息 in this Q and A

关注点分离

为了更好地分离关注点,您可以将所有与 nunjucks 相关的内容移出 app.js:

// helpers/nunjucks-helper.js:
const nunjucks = require('nunjucks');

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

  // register custom helper
  env.addFilter('shorten', function(str, count) {
    return str.slice(0, count || 5);
  });
  // ... your other filters here
}

这让您的 app.js 看起来干净多了:

// app.js
const setUpNunjucks = require('./helpers/nunjucks_helpers.js');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'html');
setUpNunjucks(app);

我的原始代码中有一个错误,导致它出现在斯通回答的关注点分离部分。这是一个很好的提示,如果您更改该块以正确设置 nunjucks env 变量,则一切正常:

// helpers/nunjucks-helper.js:
const nunjucks = require('nunjucks');

function setUpNunjucks(expressApp) {
  // set variable
  const env = nunjucks.configure('views', {
    autoescape: true,
    express: expressApp
  });

  // register custom helper
  env.addFilter('shorten', function(str, count) {
    return str.slice(0, count || 5);
  });
  // ... your other filters here
}