17

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?

2 Answers 2

24

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)

2
  • If the string contains </script> this will create problems because the browser will think it's the closing tab of the opening <script>. Is there any simple solution for that?
    – hytromo
    Feb 13, 2018 at 21:25
  • is there a way to do this the opposite way? pug allows say with an dynamic array that is created after the page renders? Nov 8, 2020 at 17:13
4

In this case I used this:

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

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

1
  • 1
    as in dNitro's answer, Using !{JSON.stringify(y)} removes the escaping issue.
    – Matt
    Jan 31, 2017 at 23:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.