How can I define global variables in nunjucks?

 ̄綄美尐妖づ 提交于 2019-12-01 01:54:46

问题


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.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/20822726/how-can-i-define-global-variables-in-nunjucks

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!