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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With