简体   繁体   中英

How to pass an object from pug to front end javascript

I´m using pug and I want to pass a variable to the front end for information, but when I´m trying to do that it pass like a text.

This is how I do that.

Controller code:

res.render('view/edit', {
     title: 'Title',
     sub:true,
     data: variableObject
 });

This is the code in the rendered view:

script(type='text/javascript').
    var x = "#{data}"
    console.log(x);

And this is the result of the log

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]

I can´t access to the object because is text, is there a way to pass the object like an object?

First stringify your object using JSON.stringify :

res.render('view/edit', {
     title: 'Title',
     sub: true,
     data: JSON.stringify(variableObject)
 });

Then use String Interpolation, Unescaped !{data}

script(type='text/javascript').
    var x = !{data}
    console.log(x);


Or just do it all once, in your template:

 script(type='text/javascript'). var x = !{JSON.stringify(data)} console.log(x); 

(kudos to @Matt, Thanks)

In this case I used this:

var x = "#{ JSON.stringify(y) }"
   console.log( JSON.parse(x.replace(/"/g,'"')) );

I´m not sure if this is the best practice.

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