Search code examples
node.jsexpressnunjucks

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


Im a little stuck and was wondering if somebody could help me please.

I have an express application and i want to add global variables to the nunjucks rendering engine.

Im aware of the nunjucks addGlobal (http://mozilla.github.io/nunjucks/api.html#addglobal) method docs here but do not know how to tie an environment into my current config block. As it appears to not be functioning i assume its something to do with my setup.

Here is what i have for my config setup:

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

As you can see i followed the docs and in my template i have {{logged_in}} but it does not show anything. Now my other render variables work fine. But i think i need to somehow link my env to my nunjucks configuration ?

Any help on the matter would be greatly appreciated. Ill be sure to update you if i make any more progress but i have been trying for a full day now so if anyone can spot the issue i would thank you greatly.

Thanks in advance for any help i get.


Solution

  • Use 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).