Accessing Express.js local variables in client side JavaScript Accessing Express.js local variables in client side JavaScript express express

Accessing Express.js local variables in client side JavaScript


When rendering is done, only the rendered HTML is send to the client. Therefore no variables will be available anymore. What you could do, is instead of writing the object in the input element output the object as rendered JavaScript:

script(type='text/javascript').    var local_data =!{JSON.stringify(data)}

EDIT: Apparently Jade requires a dot after the first closing parenthesis.


I do it a little differently. In my contoller I do this:

res.render('search-directory', {  title: 'My Title',  place_urls: JSON.stringify(placeUrls),});

And then in the javascript in my jade file I use it like this:

var placeUrls = !{place_urls};

In this example it's used for the twitter bootstrap typeahead plugin. You can then use something like this to parse it if you need to :

jQuery.parseJSON( placeUrls );

Notice also that you can leave out the locals: {} .


Using Jade templating:

If you are inserting @Amberlamps snippet of code above an included static HTML file, remember to specify !!! 5 at the top, to avoid having your styling broken,in views/index.jade:

!!! 5script(type='text/javascript')    var local_data =!{JSON.stringify(data)}include ../www/index.html

This will pass in your local_data variable before the actual static HTML page loads, so that the variable is available globally from the start.

Serverside (using Jade templating engine) - server.js:

app.set('views', __dirname + '/views');app.set('view engine', 'jade');app.get('/', ensureAuthenticated, function(request, response){    response.render('index', { data: {currentUser: request.user.id} });});app.use(express.static(__dirname + '/www'));