Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 261
kentor Avatar asked May 06 '26 19:05

kentor


2 Answers

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

like image 185
undefined Avatar answered May 09 '26 09:05

undefined


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

like image 25
MadPapo Avatar answered May 09 '26 08:05

MadPapo