在 Mojolicious 下一次可以有多個閃信嗎?我有一個表單可能有多個錯誤的情況,我希望能夠一次列出所有錯誤訊息,而不是找到一個錯誤,顯示一個錯誤,讓用戶修復一個錯誤,重復其他錯誤。
在此示例中,在一個頁面中設定訊息,然后在另一個頁面中顯示,僅顯示最后添加的訊息。
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>
謝謝你。
uj5u.com熱心網友回復:
Flash 資料存盤在散列中。'msg'每次呼叫時都會覆寫 key 的值flash()。您可以使用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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/506226.html
