Reputation: 15
ANSWER: I found out that data
is not passed down to the nunjucks template. I replaced {{data.title}}
and {{data.sub}}
with {{title}}
and {{sub}}
in index.njk and now my template renders the object variables. Thanks antonmyrberg & petarr.
I am trying to pass an object to my nunjucks template, the object is located with res.render in a module that is being exported to the express router. When I access the route, index.njk renders but the object properties do not display.
app.js
// -- Create express application --
const express = require('express');
const app = express();
// Require in Express Router
const router = require('./router');
// Require in Nunjucks and configure nujucks to install to Express
const nunjucks = require('nunjucks');
nunjucks.configure('views', {
express: app
});
// index page
app.use('/', router);
// -- Listen on port 3000 --
app.listen(3000, () => {
console.log('Listening on Port 3000');
});
router/index.js
const express = require('express');
const router = express.Router();
let index = require('../modules/index.js');
router
.route('/')
.get(index.landing);
module.exports = router;
I run the same template using app.get from app.js passing in the route and the using the same code located in module.exports.landing, the variables in the object displayed when the template rendered. But I cannot get it working with this layout.
modules/index.js
module.exports.landing = (req, res) => {
console.log('works');
let data = {
title: 'Nunjucks',
sub: 'Using nunjucks'
} ;
res.render('index.njk', data);
}
views/index.njk
<body>
<h1>{{data.title}}</h1>
<p>{{data.sub}}</p>
</body>
Upvotes: 0
Views: 2146
Reputation: 15
I found out that data
is not passed down to the nunjucks template. I replaced {{data.title}}
and {{data.sub}}
with {{title}}
and {{sub}}
in index.njk and now my template renders the object variables.
Upvotes: 0
Reputation: 36
You dont need that data when call local variables in view file, when you call
res.render('index.njk', data);
its same as
res.render('index.njk', {title: 'Nunjucks', sub: 'Using nunjucks'});
So to answer you, try to write this in template: ```
<body>
<h1>{{title}}</h1>
<p>{{sub}}</p>
</body>
```
Upvotes: 1
Reputation: 26
Haven't used Nunjucks myself, but I'd take a guess and say that you're misunderstanding how things work.
let data = {
title: 'Nunjucks',
sub: 'Using nunjucks'
};
res.render('index.njk', data);
can also be achieved by just returning an anonymous {}
.
res.render('index.njk', {
title: 'Nunjucks',
sub: 'Using nunjucks'
});
Your reference to data
is not passed down to the template, only an object containing title
and sub
. Have you tried just referencing {{title}}
and {{sub}}
?
Upvotes: 1