1

I have a node express app, and I am attempting to pass a variable through when rendering my index.hbs file, like so:

<!DOCTYPE html>
<html>
<body>
    Hello.

    <a href="/auth/facebook">Login with Facebook</a>

    {{req}} <!-- this works fine(ish) -->

    <script>
    var request = {{req}}; // This throws an error
    console.log(request);
    </script>
</body>
</html>

The {{req}} template variable gets outputted as [object Object] as expected, but when attempting to pass it through via javascript, I get Unexpected identifier thrown in console. I tried modifying to use triple curly braces instead of double curly braces but that didn't seem to make a difference.

What is the correct way to set template variables using javascript?

2 Answers2

2

This is because your template engine is replacing {{req}} with only strings.

If you want to use {{req}} in your javascript tag. Using JSON.stringify(req) to pass in template engine as parameter and in your javascript tags using triple "triple-stash" {{{req}}} to parse the string into object

About triple-stash the doc can be found http://handlebarsjs.com/ in HTML Escaping part

Hope it helps

Edited:

Find similar answer here Passing an object to client in node/express + ejs?

yue you
  • 2,206
  • 1
  • 12
  • 29
1

I had this same problem with EJS. I was able to pass the object from my Express server to the template by stringifying the object:

//express server
res.render('index', {req: JSON.stringify(data)})

//template
var request = {req}
JJJ
  • 3,314
  • 4
  • 29
  • 43