I have some Nunjucks template blocks that I want to render only in certain environments. I can't seem to access the NODE_ENV
variable though. I tried this:
{% if process.env.NODE_ENV === 'development' %}
<div>rendering some stuff here</div>
{% endif %}
This didn't seem to work for me though. It didn't seem to have any idea what process.env.NODE_ENV
was.
Is it possible to access an environment variable like this in a template?
You can use one of these variants:
Use addGlobal
to define function which returns environment
var nunjucks = require('nunjucks'); var env = nunjucks.configure(); env.addGlobal('$environment', () => process.env.NODE_ENV || 'development'); var res = nunjucks.renderString(`{{$environment()}}`); console.log(res);
Define $environment
as global .
Set res.locals.environment
in middleware
const app = express(); app.use(function (req, res, next) { res.locals.$environment = process.env.NODE_ENV || 'development'; next(); }); // In nunjucks template {{$environment}}
I ended up doing the following in my app.js
nunjucks.configure('views', {
...
}).addGlobal('NODE_ENV', process.env.NODE_ENV)
This simply adds NODE_ENV
as a globally accessible variable in my Nunjucks template.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.