Express.js View “globals”

后端 未结 7 1691
太阳男子
太阳男子 2020-12-24 01:16

I\'m using Express.js (on Node.js) and I know that you can render a view with custom data via the \"locals\" parameter. (res.render(\"template\", { locals: { foo: \"ba

7条回答
  •  旧巷少年郎
    2020-12-24 01:37

    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'
    }
    

提交回复
热议问题