Express&把手 [英] Global properties in Express & Handlebars
问题描述
在NodeJS应用程序中,我使用Handlebars(使用express3-handlebars)进行模板和Passport验证。所有的工作都很好,但是我想知道是否有办法将Passport创建的req.user对象全局传递给Handlebars。
I'm using Handlebars (using express3-handlebars) for templates and Passport for authentication in a NodeJS app. All is working great but I wondered if there is a way to pass the req.user object created by Passport to Handlebars globally.
所以我的头部分可能看起来像这样:
So my header partial might look something like this:
<header>
<h1>My Title</h1>
{{#if user}}
<p>Hello {{user.name}}</p>
{{else}}
<p>Please <a href='/login'>Log In</a></p>
{{/if}}
</header>
因为这样,我必须明确地传递每个页面渲染的用户对象:
As it stands I have to pass the user object explicitly with every page render:
app.get('/', function(req, res){
res.render('home', {
page_title: 'welcome',
user: req.user
});
});
这似乎是错误的方法,因为我需要它在每一页,我不能只需设置一次,所有页面都可以访问?
This seems like the wrong way to go about it as I require it on every page, can I not just set it once and have all pages have access to it?
当我实例化Handlebars时,我不能这样做,因为它依赖于用Passport登录的用户,将不会总是这样。
I can't do this when I instantiate Handlebars as it's dependent on the user being logged in with Passport, which won't always be the case.
将创建一个全局的page_options对象,将其附加并传递给每个渲染都是正确的解决方案或Handlebars / Express具有一个处理这个问题的方法?
Would creating a global 'page_options' object, appending and passing it to every render be the right solution or does Handlebars/Express have a way to handle this?
推荐答案
我以前没有亲自使用护照,但是基于护照README,使用其他身份验证方案,这应该是有效的。
I haven't personally used Passport before, but based on the Passport README and what I've done with other authentication schemes, this should work.
Express 3
app.configure(function() {
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
next();
});
app.use(app.router);
});
Express 4
app.use(passport.initialize());
app.use(passport.session());
app.use(function(req, res, next) {
res.locals.user = req.user; // This is the important line
next();
});
基本上,渲染之前,您的 app.locals
, res.locals
,您传递给render函数的当地人(第二个参数)都被合并并传递给您的视图引擎。
Basically, right before rendering, your app.locals
, res.locals
, and the locals you pass into the render function (the second argument) all get combined and passed along to your view engine.
这篇关于Express&把手的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!