【问题标题】:EJS in HTML not workingHTML中的EJS不起作用
【发布时间】:2014-08-05 14:01:54
【问题描述】:

这是 HTML 中 EJS 技术的正确语法吗? “闪存对象”是从控制器发送的。这是我在控制器和 HTML 代码中的“登录”操作。我希望基于“flash object”的内容执行 HTML 的和平。但它不起作用。这是后端控制器:

login: function(req, res){
      var x = new LdapService();
      x.login(req.body.userid, req.body.password, function(isAuth){
          if(isAuth ){
              res.send('successful login');
          }
          else{
              res.view('login/index', {locals: {flash: req.flash('error', 'Wrong Credentials')}}) ;
          }
      });
  },

============================================== 这是前端的HTML代码。

 <% if (req.flash('error')!=''){  %>
                <p>Hi</p>
                <p><%- (req.flash('error')) %></p>
                <div class="box-body">
                    <div class="alert alert-danger alert-dismissable">
                        <i class="fa fa-ban"></i>
                        <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
                        <b>Alert!</b> Wrong
                    </div>
                </div>
            <% } %>

【问题讨论】:

  • 显然 if (req.flash('error')!='') 不是正确的条件。它里面的块,从未执行过。
  • 我也试过 if(req.flash('error')=='Wrong Credentials') 。它不起作用。'Wrong Credentials' 是来自我的控制器的字符串。它在 flash 对象内部。我测试了它。但我不知道如何写 if 条件..

标签: html frontend sails.js ejs


【解决方案1】:

一旦您使用req.flash 访问闪存对象,它的值就会被清除。所以条件测试会清除flash对象。

该值也存储在会话中,所以我在显示闪存值之前直接测试会话。

<% if(req.session.flash && req.session.flash.error){ %>
    <div class="row form-row m-l-20 m-r-20 xs-m-l-10 xs-m-r-10">
        <div class="alert alert-error">
            <button class="close" data-dismiss="alert"></button>
            <%- req.flash('error') %>
        </div>
    </div>

<% }%>

【讨论】:

    【解决方案2】:

    在这种情况下为什么需要使用 Flash 消息并不完全清楚,因为您正在设置消息并在同一个请求中显示它。当您设置消息然后重定向时,Flash 消息更合适,因为重定向之前的代码没有机会直接设置视图本地值。你可以这样做:

    res.view('login/index', {locals: {flash: {'error':'Wrong Credentials'}}});
    

    在您的模板中:

    <% if((flash = {} || flash) && flash.error){ %>
        <div class="row form-row m-l-20 m-r-20 xs-m-l-10 xs-m-r-10">
            <div class="alert alert-error">
                <button class="close" data-dismiss="alert"></button>
                <%- flash.error %>
            </div>
        </div>
    
    <% }%>
    

    如果您是从另一个视图重定向,那么您可以使用 Flash 消息并保持相同的模板。在您从 重定向的操作中,您将设置一条 Flash 消息:

    req.flash('error', 'my error message');
    res.redirect('/someOtherLoginRoute');
    

    在您重定向到的操作中,执行:

    res.view("login/index", {locals: {flash: req.flash()}});
    

    这是一个人为的例子,但你有它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-14
      • 2016-07-19
      • 2012-05-01
      • 2018-05-26
      相关资源
      最近更新 更多