Pass JSON as javascript variable in pug

Viewed 5195

I want to pass an array of objects into my javascript code block but I am struggling because it would html encode the result so that I've got a lot of " in my actual JSON.

Basically my router gets the JSON object from the redis store and I am trying to pass it to the template:

redis.getBuffer('languages', function (err, result) {
    res.render('manager/create-project', { title: 'Create Project', breadcrumbs: req.breadcrumbs(), languages: result })
})

I assign it like this to my variable:

script.
    $(document).ready(function() {
        var languages = #{languages};

The problem: The actual javascript variable languages gets the html encoded string as shown below.

var languages = [{"id":"aa","text":"Afar"}]

How can I properly pass my JSON content to the javascript block?

3 Answers

This worked for me:

NodeJs:

res.render('itemdetails', {
    title: 'Donation item details',
    user: req.user,
    item: item.toJSON(),
    GOOGLE_MAP_API_KEY: process.env.GOOGLE_MAP_API_KEY
  });

Pug View:

 script.
  $(document)
    .ready(() => {
    createGlobalObjects('minimap');
    let item = !{JSON.stringify(item)};
    initLocationSearch(positionItemOnMap.bind(item));
  });

Results:

enter image description here

Related