为什么我不能在我的快递把手模板中使用if语句?

时间:2016-08-22 23:05:17

标签: node.js express handlebars.js templating

我最近开始研究我的第一个Express项目,并选择使用Handlebars作为我的模板语言,因为我在创建Ghost博客主题时有过一些经验。

我使用Passport.js创建登录屏幕,并使用connect-flash向用户发送错误消息。我可以将错误消息作为把手助手传递,但是当我尝试在把手模板中包含if语句时,即使出现错误消息,它也总是假的。

这是我的代码:

login.js(路线)

app.route('/login')
    .get(function(req, res) {
        if (req.isAuthenticated()) {
            res.redirect('/');
        } else {
            res.render('login', {
                helpers: {
                    message: req.flash('loginMessage')
                }
            });
        }
    })
    .post(...);

login.handlebars

<form action="/login" method="post">
    <div>
        <label>Email</label>
        <input type="text" name="email">
    </div>
    <div>
        <label>Password</label>
        <input type="password" name="password"> 
    </div>
    <button type="submit">Log In</button>
</form>

{{#if message}}
    <p style="color: red">{{message}}</p>
{{/if}}

这没有if语句:

<p style="color: red">{{message}}</p>

但我不喜欢在我的html中拥有空元素的想法。我非常感谢任何帮助,因为我确信我错过了一些非常简单的事情。

感谢。

2 个答案:

答案 0 :(得分:1)

我相信你必须使用subexpression才能在一个小胡子中调用多个助手。修复就像添加括号一样简单:

{{#if (message)}}
    <p style="color: red">{{message}}</p>
{{/if}}

修改

请注意,上面假设helpers.message处的对象类型是辅助函数为Handlebars documentation状态的函数。但是,connect-flash documentation表示req.flash('loginMessage')将返回一个数组。在这种情况下,结果不应该分配给帮助程序,而应该是视图模型对象的常规值:

res.render('login', {
    messages: req.flash('loginMessage')
});

在我们的模板中,由于messages是一个数组,我们必须查找并访问其第0个元素:

{{#if (lookup messages 0)}}
    <p style="color: red">{{messages.[0]}}</p>
{{/if}}

答案 1 :(得分:0)

这可能来得太晚了,但对于那些将来仍会遇到此问题或相关问题的人,我希望这对您有用。 另一种方法是使用 res.redirect('/login'); 而不是 res.render('login)

将此添加到您的 SERVER/INDEX.JS

const flash = require('connect-flash');//import this guy
    app.use(flash());
    app.use(function(req, res, next) {
    res.locals.message = req.flash('loginMessage'); 
    next();
  });

您的 LOGIN.JS 将如下所示

  app.route('/login')
   .get(function(req, res) {
     if (req.isAuthenticated()) {
        res.redirect('/');
        return;//you should always return if there's no more thing to do
     } else {
       req.flash('loginMessage', 'your message here');
       res.redirect('/login');
       return;//you should always return if there's no more thing to do
    };
  })
  .post(...);

上述方法使您可以更轻松地重复使用您的消息。例如,您只需将 req.flash('loginMessage', 'your message here'); 更改为此 req.flash('loginMessage', 'another message here'); 即可重复使用上述消息。

您还可以通过将所有错误和成功消息移动到 PARTIAL 文件夹中,然后通过在所有页面中插入此 {{>yourMessages}} 在前端的所有其他页面中使用它来重复使用整个消息。

您的 LOGIN.handlebars

 <form action="/login" method="post">
   <div>
    <label>Email</label>
    <input type="text" name="email">
   </div>
   <div>
    <label>Password</label>
    <input type="password" name="password"> 
   </div>
   <button type="submit">Log In</button>
 </form>

 {{#if message}}
  <p style="color: red">{{message}}</p>
 {{/if}}