Express.js View “globals”

It’s worth noting for those who may have come across this question since the release of Express 3, that the method ‘dynamicHelpers’ no longer exists.

Instead you can use the app.locals function, which acts as an object you can store values or functions in, and then makes them available to views. For example:-

// In your app.js etc.
app.locals.title = "My App";
app.locals({
    version: 3,
    somefunction: function() {
        return "function result";
    }
});

// Then in your templates (shown here using a jade template)

=title
=version
=somefunction()  

// Will output

My App
3
function result

If you need access to the request object to pull information from, you can write a simple middle-ware function and use the app.settings variable.

For example, if you are using connect-flash to provide messages to your users, you might do something like this:

app.use(function(req, res, next) {
    app.set('error', req.flash('error'));
    next();
});

Which would give you access to the error message with =settings.error in your template.

These topics are covered here, albeit slightly briefly: http://expressjs.com/api.html#app.locals

Update: Express 4

app.locals is now a simple JavaScript Object, so every property has to be set one by one.

app.locals.version = 3;
app.locals.somefunction = function() {
    return "function result";
}

res.locals provides the exact same functionality, except it should be used for request-specific data rather than application-wide data. A user object or settings is a common use case.

res.locals.user = req.isAuthenticated() ? req.user : null;
res.locals.userSettings = {
    backgroundColor: 'fff'
}

Leave a Comment