Accessing Express.js local variables in client side JavaScript

瘦欲@ 提交于 2019-11-26 18:28:44

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:

!!! 5
script(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'));

You don't need to pass the locals variables in render call, locals variables are globals. On your pug file call don't put keys expression e.g #{}. Just use something like: base(href=base.url)

where base.url is app.locals.base = { url:'/' };

Have you heard of socket.io? (http://socket.io/). An easy way to access the object from express would be to open a socket between node.js and your javascript. This way data can be easily passed to the client side and then easily manipulated using javascript. The code wouldn't have to be much, simply a socket.emit() from node.js and a socket.on() from the client. I think that'd be an effective solution!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!