Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get object's value in Pug?

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?

like image 292
laoqiren Avatar asked Sep 24 '16 13:09

laoqiren


People also ask

What is JavaScript object value?

Object. values() returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

How do you compile a pug?

The general rendering process of Pug is simple. pug. compile() will compile the Pug source code into a JavaScript function that takes a data object (called “ locals ”) as an argument. Call that resultant function with your data, and voilà!, it will return a string of HTML rendered with your data.


1 Answers

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

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

See Pug documentation for interpolation.

like image 134
Michał Perłakowski Avatar answered Sep 28 '22 05:09

Michał Perłakowski