我如何在全局变量的快速应用程序中使用 nunjuck 环境?

How do i use nunjuck environments in side an express application for global variables?

我有点卡住了,想知道是否有人可以帮助我。

我有一个快速应用程序,我想将全局变量添加到 nunjucks 渲染引擎。

我知道这里有 nunjucks addGlobal (http://mozilla.github.io/nunjucks/api.html#addglobal) 方法文档,但不知道如何将环境绑定到我当前的配置块中。由于它似乎无法正常工作,我认为它与我的设置有关。

这是我的配置设置:

const viewFolders = [
  path.join(__dirname, '..', 'views')
];

// *** view engine *** //
nunjucks.configure(viewFolders, {
  express: app,
  autoescape: true
});
var env = new nunjucks.Environment(new nunjucks.FileSystemLoader('views'));
console.log(env);
env.addGlobal('logged_in','FROM Module');
app.set('view engine', 'html');

如您所见,我遵循了文档,在我的模板中有 {{logged_in}} 但它没有显示任何内容。现在我的其他渲染变量工作正常。但我想我需要以某种方式 link 我的环境到我的 nunjucks 配置?

如有任何帮助,我们将不胜感激。如果我取得更多进展,我一定会更新你,但我已经尝试了一整天,所以如果有人能发现问题,我会非常感谢你。

提前感谢我得到的任何帮助。

使用res.locals:

An object that contains response local variables scoped to the request, and therefore available only to the view(s) rendered during that request / response cycle (if any).

配置块也是如此。您需要将其设置为一个变量,然后引用它以设置全局变量。

例如

var env;
env = nunjucks.configure(viewFolders, {
  express: app,
  autoescape: true
});
env.addGlobal('logged_in','FROM Module');