Javascript 使用快速闪光手柄?

Javascript 使用快速闪光手柄?,javascript,express,Javascript,Express,我正在学习使用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) { %> <%

我正在学习使用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 %>
<% } %>
但是,如果如第一个示例所示重新格式化路由器代码,我的
注册
路由会出现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());
除此之外,我还不确定如何使用handlebar复制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
    }
};
“严格使用”;
const=require('lodash');
让_req,_res;
//为flash消息构建html。
函数renderFlashMsg(){
让flash=_req.flash(),
out='',
类型=[“成功”、“错误”、“信息”];
_.每个(类型)(类型)=>{
if(闪存[类型]){
out+='';
out+=''+类型+'';
out+='
    '; _.每个(闪存[类型],(消息)=>{ out+=`
  • ${msg}
  • `; }) ; out+='
'; } }); 返回; } module.exports={ “setContext”:(请求、恢复、下一步)=>{ _req=req; _res=res; next(); }, “助手”:{ renderFlashMsg } };
现在,您可以在
主布局文件中使用
renderFlashMsg


{{{renderFlashMsg}}}
放在希望在DOM中放置flash消息的位置。

是否设置了把手模板的视图引擎

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

或者将文件扩展名更改为.handlebar

您是否正在使用
handlebar
express handlebar
?抱歉。快速车把
app.engine('handlebars', exphbs({/* config */}));
app.set('view engine', 'handlebars');