Accessing Express.js req or session from Jade template

后端 未结 7 1242
南方客
南方客 2020-12-13 18:49

I am wondering if there is an easy way to access Express.js\' req or session variables from within a Jade template without passing it in through the normal response.

7条回答
  •  北海茫月
    2020-12-13 19:35

    You could solve this with a render function in which you use to render every view that needs the session variable as a local variable accessible in the template(usually when a user is logged in for example).

    Here is an example of a function but you can adjust as you like:

    var renderView = function(res, template, context, session, cb) {
        context.session = session;
    
        if(cb){
            res.render(template, context, function(error, html){
                cb(error, html)
            }
        } else {
            res.render(template, context)
        }
    }
    

    Then it can be used like this:

    app.get("/url", function(req, res){
    
        req.session.user_email = user_email;
    
        renderView(res, "template_name", { local_variables: local_variables }, req.session)
    });
    

    and in your jade template you can access the session variables like this:

    div.user-email #{session.user_email}
    

提交回复
热议问题