如何使用Mojolicus发布多条快闪消息



在Mojolicus下一次是否可以有多条闪存消息?我有一种情况,表单可能有多个错误,我希望能够一次列出所有错误消息,而不是查找一个错误,显示一个错误、让用户修复一个错误并重复其他错误。

在这个示例中,消息在一个页面中设置,然后在另一个页面上显示,只显示最后添加的消息。

get '/' => sub {
my ($c) = @_; 
$c->flash(msg => "This is message one.");
$c->flash(msg => "This is message two.");
$c->flash(msg => "This is message three.");
$c->flash(msg => "This is message four.");
$c->flash(msg => "This is message five.");
return $c->redirect_to('/second');
};
get '/second' => sub {
my ($c) = @_; 
return $c->render(template => 'second');
};
app->secrets(["aren't important here"]);
app->start;
__DATA__
@@ second.html.ep
<!doctype html><html><head><title>Messages</title></head>
<body>
These are the flash messages:
<ul>
% if (my $msg = flash('msg')) {
<li><%= $msg %></li>
% }
</ul>
</body></html>

输出为

These are the flash messages:
This is message five.

我也尝试过在列表上下文中获取消息,但仍然只显示最后一条消息。

__DATA__
@@ second.html.ep
<!doctype html><html><head><title>Messages</title></head>
<body>
These are the flash messages:
<ul>
% if (my @msg = flash('msg')) {
%   foreach my $m (@msg) {
<li><%= $m %></li>
%   }
% }
</ul>
</body></html>

谢谢。

Flash数据存储在哈希中。每次调用flash()时,都会覆盖键'msg'的值。您可以使用flash来存储数据结构,而不是标量值:

use Mojolicious::Lite -signatures;
get '/' => sub {
my ($c) = @_; 
my @messages = map ("This is message $_", qw/one two three four/);
$c->flash(msg =>@messages);
return $c->redirect_to('/second');
};
get '/second' => sub {
my ($c) = @_; 
return $c->render(template => 'second');
};
app->secrets(["aren't important here"]);
app->start;
__DATA__
@@ second.html.ep
<!doctype html><html><head><title>Messages</title></head>
<body>
These are the flash messages:
<ul>
% for my $msg  (@{flash('msg')//[]}) {
<li><%= $msg %></li>
% }
</ul>
</body></html>

最新更新