5

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?

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
  • Where is your environment variable set and how? Maybe in your case it could be undefined, then you should set it to an default value. take a look at this: https://github.com/JohnnyDevNull/express-api-typescript-template/blob/master/src/server.ts and this: https://github.com/JohnnyDevNull/express-api-typescript-template/blob/master/package.json where i set my env variables – JohnnyDevNull Sep 12 '18 at 05:17
  • It's set in my app.js. – Jake Wilson Sep 13 '18 at 04:44

2 Answers2

4

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.

Jake Wilson
  • 88,616
  • 93
  • 252
  • 370
1

You can use one of these variants:

  1. 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);
    
  2. Define $environment as global.

  3. 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}}
    
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31