I am rendering a Jade template on an ajax call via res.render with Express. Problem is I want to pass back some JSON vars or Javscript objects along with the HTML.
Is this possible in an elegant way or at all? I know I can pass a script tag along with the HTML but I'm not sure how I can access those values directly within the 'data' response.
Example here:
- var someNumber = 89
h1 Hello World
li #{someNumber}
Normally in a res.render() of this template on an ajax call you would get back
<h1> Hello Wolrd </h1>
<li> 89 </li>
All in HTML format.
How do I access one of the HTML nodes in the callback? Ideally with a jQeury selector, such as $('h1 li'). I need access to the number in the call back but it doesn't seem to be grabbing it. I'm thinking listener or adding a delay or maybe I need to assign it to a string and parse it out.
Not entirely sure I understand the question. However, to pass JSON direct to the browser via Jade. In your route logic you need something like:
res.render "test",
title: "Test"
debugJson: {
'Read Folder Result' : result,
'HTTP' : {
'Req URL' : req.url,
'Req Query' : req.query,
'Req User' : req.user,
'Req Headers' : req.headers,
'Req' : req,
'Res' : res
}
}
(Sorry, that is in CoffeeScript rather than JS)
And in your Jade template, you need to have something like (in a script):
var myJson = !{JSON.stringify(debugJson)};
which will pass the JSON straight into the script. If you want it direct into the DOM, something like:
#debug !{JSON.stringify(debugJson)}
Which will dump it into a div.
If you just want to process it in the Jade template however, you can simply use a loop in Jade. See this previous StackOverflow question for how to do that.