11

Using nunjucks, how can I define some global variables that should always be available within all templates?

Ideally, they would be specified somewhere in the environment or config options and not have to be merged into the context dict with each call to nunjucksEnvironment.render.

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • If you happen to be using Express, you can use [`app.locals`](http://expressjs.com/api.html#app.locals) to store global variables. – robertklep Dec 29 '13 at 09:03
  • @robertklep: No Express, just Connect. – mpen Dec 29 '13 at 18:22
  • Actually, I want to use these templates client-side too, so... the solution can't have a dependency on server-side tech. – mpen Dec 29 '13 at 18:43

3 Answers3

10

It might be also helpfull for someone. It is possible to avoid writing any js code when dealing with global variables in nunjucks.

You need to create a _globals.html file, which contains all the global variables.

{% set some_var1 = "Foo" %}
{% set some_var2 = "Bar" %}

Then include _globals.html to any page, where you need the global variable. E.g. somePage.html

{% import '_globals.html' as globals %}

<span>{{globals.some_var1 }}</span>
<span>{{globals.some_var2 }}</span>

For more info please check http://mozilla.github.io/nunjucks/templating.html#set

Aliaksei Maniuk
  • 1,534
  • 2
  • 18
  • 30
  • This should be the accepted answer. No need to rebuild your js, or gulpfile with this approach, unless your global data "needs" to be JavaScript based. – klewis Nov 10 '22 at 18:38
5

It's not documented (or perhaps advised), but this works:

var njglobals = require('nunjucks/src/globals');
njglobals.someVar = 'someValue';

You can now use someVar in your templates.

Be sure not to overwrite any of the existing properties of the njglobals object, though (for nunjucks@1.0.1, they are range, cycler and joiner).

robertklep
  • 198,204
  • 35
  • 394
  • 381
  • Not sure why globals aren't advised. I want to set a "debug" environment variable, for example, to conditionally include livereload and minified files. – mpen Dec 29 '13 at 22:33
  • 1
    It's not so much not advised, it's re-using an internal part of the module because there doesn't seem to be a public API for it :) – robertklep Dec 30 '13 at 07:35
5

I was just looking for this and came here. Looks like there's now a recommended way which was added in recently in version 1.0.6.

See Environment.addGlobal.

Joe
  • 16,328
  • 12
  • 61
  • 75