简体   繁体   English

Node.js - 如何在EJS视图中使用我的局部变量

[英]Node.js - How can I use my local variable with EJS view

I try to used my local variable on EJS. 我尝试在EJS上使用我的局部变量。 It's just a varaiable to check if the user is connected. 检查用户是否已连接只是可变的。 -> Like the last post on this link: How to know if user is logged in with passport.js? - >与此链接上的最后一篇文章一样: 如何知道用户是否使用passport.js登录?

So, 所以,

app.js app.js

app.use(function (req, res, next) {
    res.locals.login = req.isAuthenticated();
    next();
});

view EJS 查看EJS

<% if (login) { %>
      <div id="subMenuUser">
        <div class="btn-group">
          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            </span>Menu<span class="caret"></span>
          </button>
          <ul class="dropdown-menu pull-right" role="menu">
            <li><a href="#" role="menuitem">Menu Item 1</a></li>
            <li><a href="#" role="menuitem">Menu Item 2</a></li>
            <li><a href="#" role="menuitem">Menu Item 3</a></li>
          </ul>
        </div>
      </div>
 <% } %>

I get an error: 我收到一个错误:

login is not defined

I would like to use this variable with all view.. possible ? 我想在所有视图中使用此变量..可能吗?

Before this method, I sent each time my variable in render like that: 在此方法之前,我每次都将我的变量发送到渲染中:

res.render('ad/index', { login: req.session.user });

Make sure that you are declaring that middleware function that sets res.locals.login before you declare your app.router. 在声明app.router之前,请确保声明设置res.locals.login的中间件函数。 This ensures that the route rendering your template does not render the template before your middleware can set res.locals.login. 这可确保在中间件设置res.locals.login之前,呈现模板的路由不会呈现模板。 Something along the lines of: 有点像:

app.use(function (req, res, next) {
    res.locals.login = req.isAuthenticated();
    next();
});

app.configure(function(){
    ...
    app.use(app.router);
    ...
});

It appears others have asked a similar question, but with other templating engines: Accessing res.locals from Backbone.Router templates 似乎其他人提出了类似的问题,但使用其他模板引擎: 从Backbone.Router模板访问res.locals

或者如果您不想创建中间件,您也可以直接在ejs文件中使用以下检查:

if(locals.login) { .... }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM