Express - data transfer on all routes

Hi, is there a “special” way to make some global application data available for all my routes? Or is this the case of using the module.exports statement?

Any pointers are more than welcome. Node noob - btw

+5
source share
3 answers

You can set a global object, which 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
+11
source

You can use app.set()the settings section of your application to make it available for each request. The application object is accessible via req.appin your routes.

app.set('name', obj); , req.app.settings.name.

+7

You can also use the dynamic assistant to transfer data to all views.

app.js

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

Now in your views you can use it like this (I used ejs in this example, but it should work with jade or any other viewing mechanism):

view.ejs

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

Hope this helps.

+2
source

All Articles