1

I've spent all of this morning searching for how to do this, and have come up stumped.

The project I'm working on is built on KeystoneJS/NodeJS. It's using Nunjucks which I've only got a few days basic experience of.

My issue is that after loading the config vars that sets the URI's/Ports of the services, I then want to set these up as Nunjucks variables, so within the html views, I can use those as the src locations.

I can't share all the code here, as I'm working on a government (UK) project but here's enough I hope.

Keystone.js

// Require keystone
var keystone = require('keystone');
var cons = require('consolidate');
var nunjucks = require('nunjucks');
var env = new nunjucks.Environment(null);

env.addGlobal('provision_uri', 3);

This loads initially, after routing it calls:

Login.js

var keystone = require('keystone');
var nunjucks = require('nunjucks');

exports = module.exports = function (req, res) {

    var view = new keystone.View(req, res);
    var locals = res.locals;

    // locals.section is used to set the currently selected
    // item in the header navigation.
    locals.section = 'home';

    var env = new nunjucks.Environment(null);
    var provision_uri = env.getGlobal('provision_uri',3);

    console.log(`Uri ${provision_uri}`); **<-- ERRORS HERE**

    // Render the view
    view.render('login', {
        title: 'User Login',
        description: 'Login to your Account',
        provision_uri: provision_uri
    });
};

Login.html

<br>
<form action="{{provision_uri}}/session" method="post" name="user">
<div class="container">

When I then start the project, the landing page loads, click on the login page and within console I get:

GET /provision/ 304 74.147 ms

Error thrown for request: /login

Error: global not found: provision_uri

I've checked this Question however it doesn't answer what I need but I looked up the environment.addGlobal given as an answer. That did seem to be what I wanted, but still it wouldn't work. I found this question which provided hope.

Any ideas would be great, I do have a work-around but would like to learn how to use these.

Thanks, Colin

Community
  • 1
  • 1

1 Answers1

0

You don't need to create new instance of nunjucks environment on each render call. The new scope (environment) has empty global space.

var nunjucks = require('nunjucks');
var env = new nunjucks.Environment(null);
env.addGlobal('provision_uri', 3);
...
exports = module.exports = function (req, res) {
    ...
    var provision_uri = env.getGlobal('provision_uri',3);
    console.log(provision_uri);

    view.render('login', {
        title: 'User Login',
        description: 'Login to your Account',
        // provision_uri: provision_uri // it's not necessary
    });
} 
Aikon Mogwai
  • 4,954
  • 2
  • 18
  • 31