Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I define global variables in nunjucks?

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.

like image 986
mpen Avatar asked Dec 29 '13 06:12

mpen


People also ask

How do you define a variable in Nunjucks?

A variable looks up a value from the template context. This documents details on the variables available in JMWE and how to create custom variables. If you want to insert the value of a variable in your template, you can use the following syntax: {{ myVar }} .

How do you define global variable in bean implementation?

A global variable is one declared at the start of the code and is accessible to all parts of the program. Since Java is object-oriented, everything is part of a class. ... A static variable can be declared, which can be available to all instances of a class.

How do I set a global variable in spring boot?

The best way we can use that is - spring cloud config server externalized configuration. We can create a microservice for spring cloud config server. In config server we can create our variables and configuration in two ways. Using local file system / Environment variables.


3 Answers

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

like image 89
Aliaksei Maniuk Avatar answered Sep 18 '22 13:09

Aliaksei Maniuk


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.

like image 30
Joe Avatar answered Sep 16 '22 13:09

Joe


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 [email protected], they are range, cycler and joiner).

like image 44
robertklep Avatar answered Sep 18 '22 13:09

robertklep