Jade / Expressjs: Pass objects from server to client

1.3k views Asked by At

I'm trying to pass an object from my endpoint to Jade but It keeps giving me Uncaught SyntaxError: Unexpected identifier on Stat! Can someone help me please. Here is my code:

app.get('/stats', function (req, res, next) {

    var stats ={
        'm0t20': {a:0,b:0,c:0,d:0},
        'm20t30': {a:0,b:0,c:0,d:0},
    };
   res.render('chart',{'stat':stats});
 }

and in my jade and I cant get the value of stat:

 script(type='text/javascript').
        var stats= #{stat};
1

There are 1 answers

0
KtorZ On BEST ANSWER

If you want to interpolate object from you express, the easiest and cleanest way is to serialize them. For the moment, once interpolated, you are trying to write something like this:

var stats = [Object object];

Which isn't a valid JavaScript syntax :/ So, on the server side, serialize your object:

 app.get(..., function (req, res) {
    var stats = { ... };
    res.render('chart', { stats: JSON.stringify(stats) });
 });

And, on the client side, just use the serialized object; You'll need to use ! instead of # to prevent jade from escaping characters like quotes.

script.
    var stats = !{stats};
    alert(stats.myProp);

Keep in mind that you are injecting direct JavaScript code into your page.
DO NOT do that if the serialized object could contain any user input