Chin
Chin

Reputation: 12712

Express - Passing data to all routes

Hi is there a 'express' specific way to make some global app data available to all my routes? Or is it a case of just using an module.exports statement?

Any pointers more than welcome. Node noob - btw

Upvotes: 5

Views: 6711

Answers (3)

Pastor Bones
Pastor Bones

Reputation: 7351

You can set a global object that is also available in your layout

app.js

app.configure(function(){
  app.set('view options', {pageTitle: ''});
});

app.get('/',function(request, response){
  response.app.settings['view options'].pageTitle = 'Hello World';
  response.render('home');
});

layout.jade

!!!
html
  head
    title= pageTitle
  body!= body

Upvotes: 11

FMontano
FMontano

Reputation: 927

You could also use a dynamic helper to pass data to all views.

app.js

// Dynamic Helpers
app.dynamicHelpers({
    appSettings: function(req, res){
        return {name:"My App", version:"0.1"};
    }
});

Now on your views you can use it like this (I used ejs on this example but it should work with jade or any other view engine):

view.ejs

<%= appSettings.name %> 
<%= appSettings.version %> 

Hope this helps.

Upvotes: 2

staackuser2
staackuser2

Reputation: 12412

You can use app.set() in the setup portion of your app to make it available to each request. The app object is available via req.app in your routes.

Personally, I like to do an app.set('name', obj); in the setup and in the routes I access it via req.app.settings.name.

Upvotes: 7

Related Questions