gpt4 book ai didi

node.js - 如何将 Nunjucks addfilter 函数放在 app.js 以外的 Express.js 文件中?

转载 作者:搜寻专家 更新时间:2023-11-01 00:28:29 25 4
gpt4 key购买 nike

我正在我的 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

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

最佳答案

最少的代码更改

在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);

关于node.js - 如何将 Nunjucks addfilter 函数放在 app.js 以外的 Express.js 文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48331121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com