简体   繁体   中英

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.

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 });

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM