繁体   English   中英

在车把上使用Express-Flash?

[英]Using express-flash with Handlebars?

我正在关注使用ejs5的教程。 该教程希望我使用Express-Flash,并像这样组织我的routes/users页面。

router.get('/signup', function(req, res, next){
    res.render('accounts/signup', {
        errors: req.flash('errors')
    });
});

后续的es5如下所示:

<% if (errors.length > 0) { %>
<%= errors %>
<% } %>

对于我自己,我使用Express-Handlebars。 现在,我知道我的app.js文件具有所需的一切,因为到/signup路由如下所示:

router.get('/signup', function(req, res, next){
    res.render('accounts/signup');     
 });

但是,如果如第一个示例所示重新格式化我的路由器代码,则在我的signup路线上会收到404错误。 我不明白为什么会这样。 为了演示,这就是我所拥有的,与第一个示例相同。

//render the signup//
router.get('/signup', function(req, res, next){
    res.render('accounts/signup', {
        errors: req.flash('errors')
    });
});  

可以肯定的是,我的主要app.js文件包含以下内容:

var flash = require('express-flash');
app.use(flash());

除此之外,我也不确定如何使用Handlebars复制ejs脚本。 会做这样的事情吗?

{{#if errors.length > 0}}
     {{errors}}
{{/if}}

我无法进行测试,因为我首先需要显示注册路线。

您可以注册Flash助手,并在主模板中使用它。

// set context for the req, res
app.use(require('./../web/helpers/view').setContext);

exphbs.create({
    extname      :'hbs',
    layoutsDir   : '/path/',
    defaultLayout: 'main',
    helpers      : require('/path/to/view').helpers, // this is where you can register a helper.
    partialsDir  : [
        '/path/'
    ]
});

view.js ,编写一种从Flash消息构建HTML的方法。

'use strict';

const _ = require('lodash');

let  _req, _res;

// build html for flash messages. 
function renderFlashMsg() {
    let flash = _req.flash(),
        out   = '',
        types = ['success', 'error', 'info'];

    _.each(types, (type) => {
        if (flash[type]) {
            out += '<div class="flash-msgs '+ type +'">';
            out += '<h2><span>' + type + '</span></h2>';
            out += '<ul>';

            _.each(flash[type], (msg) => {
                out += `<li>${msg}</li>`;
            }) ;

            out += '</ul></div>';
        }
    });

    return out;
}

module.exports = {
    'setContext': (req, res, next) => {
        _req = req;
        _res = res;
        next();
    },
    'helpers': {
        renderFlashMsg
    }
};

现在您可以在main布局文件中使用renderFlashMsg了。

{{{renderFlashMsg}}}放在要在DOM中放置Flash消息的位置。

您是否为车把模板设置了视图引擎?

app.engine('handlebars', exphbs({/* config */}));
app.set('view engine', 'handlebars');

或将文件扩展名更改为.handlebars

暂无
暂无

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

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