简体   繁体   中英

Pass JSON as javascript variable in pug

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?

You need to interpolate without escaping. This can be achieved by using ! instead of # .

For example, changing your template to the following should solve your issue:

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

For reference, here's the link to the docs

The working way to do that is (I know is horrible but PUG works like this)

script(type="text/javascript").
    $(document).ready(function(){
       var languages = !{JSON.stringify(languages)}
    });

Working on 2018

More info on http://www.mircozeiss.com/how-to-pass-javascript-variables-from-a-server-to-angular

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:

在此处输入图片说明

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