dima dima - 2 months ago 20
Node.js Question

passing an object to nunjucks template in node express

I am passing an object in Express to a Nunjucks template

app.get('/purchase', function (req, res) {

purchase_data = JSON.stringify(req.query);
res.render('purchase', {"purchase": purchase_data});

})

------------------------

<ul>
{% for key,value in purchase %}
<li>{{key}} | {{value}}</li>
{% endfor %}
</ul>


The output is literally each and every letter of the value property. For example: {"quantity": "1"} becomes
0 | {
1 | "
2 | q
3 | u
4 | a
5 | n
6 | t
7 | i
8 | t
9 | y
10 | "
11 | :
12 | "
13 | 1
14 | "

Not that experiences with nunjucks, and for that matter express, but this is a common enough task. In nudge in the right direction would be very much appreciated.

Answer

I am passing an object in Express to a Nunjucks template

No, you're not. You're passing a string:

purchase_data = JSON.stringify(req.query);           // make a string
res.render('purchase', {"purchase": purchase_data}); // pass the string to the template

Instead, just pass the object as-is:

res.render('purchase', { purchase : req.query });
Comments