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?
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.
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.
Use JSON.stringify()
and change #
to !
to prevent the quotes from being escaped:
script.
window.user = !{JSON.stringify(user)}
See Pug documentation for interpolation.
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