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
A standard middleware function always follows a signature with the three arguments (req, res, next) where req is the incoming request, res the response to be sent and next a reference to a function for stepping to the next middleware function.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware. Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects.
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)}')
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.
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