7

I'm using Node.js to render a page using Pug. My JavaScript code:

router.get('/', function(req, res, next) {
  res.render("index",{
    title:"首页",
    user:{name:"luo",age:19}
  });
});

My Pug code:

script.
    window.user = #{user}

But the result is like this:

<script>window.user = [object object]</script>

How to get the object's value correctly?

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
laoqiren
  • 3,457
  • 5
  • 19
  • 29

1 Answers1

12

Use JSON.stringify() and change # to ! to prevent the quotes from being escaped:

script.
    window.user = !{JSON.stringify(user)}

See Pug documentation for interpolation.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177