Nick White
Nick White

Reputation: 1612

ExpressJS Pass variables to JavaScript

I am completely lost on this; I am using NodeJS to fetch a JSON and I need to pass the variable to my page and have JavaScript use the data.

app.get('/test', function(req, res) {
    res.render('testPage', {
        myVar: 'My Data'
    });

That is my Express code (very simple for testing purposes); now using JADE I want to gather this data which I know to render on the page is simply

p= myVar

But I need to be able to gather this data in JavaScript (if possible within a .js file) but for now just to display the variable in an Alert box I have tried

alert(#{myVar})

And many others if anyone can help be much appreciated

Upvotes: 14

Views: 11403

Answers (5)

Bennit
Bennit

Reputation: 428

As Timothy said:

<script type="text/javascript"> var myVar = #{JSON.stringify(myVar)}; </script>

This can also be done as follows in if you don't like to write HTML in Jade/Pug templates:

script
  var myVar = !{JSON.stringify(myVar)};
  var myVar2 = !{JSON.stringify(myVar2)};

Update: For Express 4 and Pug use script. instead of script so that it will be rendered as javascript instead of html.

Upvotes: 11

dzajdband
dzajdband

Reputation: 301

Try the following:

alert('!{myVar}')

It's a good idea to JSON encode the data if is more than just a string.

alert('!{JSON.stringify(myVar)}')

Upvotes: 11

BFree
BFree

Reputation: 103740

I know I'm a bit late to the party, but I actually wrote a module (JShare) a few months ago to solve this exact problem. Check it out: https://npmjs.org/package/jshare

Upvotes: 0

JP Richardson
JP Richardson

Reputation: 39395

You could leverage Now.js for this. It easily allows you to share variables client/server side real-time.

Check it out: http://www.nowjs.com/

Upvotes: -2

Timothy Meade
Timothy Meade

Reputation: 2506

Well, Javascript (and V8) has a built in function to render JSON from a object, and JSON happens to be syntactially compatible with Javascript.

So the easiest way to do what your trying to do would be:

<script type="text/javascript>var myVar = #{JSON.stringify(myVar)};</script>

And, yes, you can use HTML in a Jade template.

Upvotes: 3

Related Questions