在 Laravel 中,在 session 中传递不同类型的 flash 消息的最佳方式 [英] In Laravel, the best way to pass different types of flash messages in the session
问题描述
我正在 Laravel 中制作我的第一个应用程序,并试图让我的头脑了解会话闪存消息.据我所知,在我的控制器操作中,我可以通过设置来设置一条闪光消息
I'm making my first app in Laravel and am trying to get my head around the session flash messages. As far as I'm aware in my controller action I can set a flash message either by going
Redirect::to('users/login')->with('message', 'Thanks for registering!'); //is this actually OK?
对于重定向到另一个路由的情况,或者
For the case of redirecting to another route, or
Session::flash('message', 'This is a message!');
在我的主刀片模板中,我将拥有:
In my master blade template I'd then have:
@if(Session::has('message'))
<p class="alert alert-info">{{ Session::get('message') }}</p>
@endif
您可能已经注意到,我在我的应用程序中使用 Bootstrap 3,并希望使用不同的消息类:alert-info
、alert-warning
, alert-danger
等
As you may have noticed I'm using Bootstrap 3 in my app and would like to make use of the different message classes: alert-info
, alert-warning
, alert-danger
etc.
假设在我的控制器中我知道我正在设置什么类型的消息,那么在视图中传递和显示它的最佳方式是什么?我是否应该在会话中为每种类型设置单独的消息(例如 Session::flash('message_danger', 'This is a nasty message!Something's wrong.');
)?然后我需要为刀片模板中的每条消息使用单独的 if 语句.
Assuming that in my controller I know what type of message I'm setting, what's the best way to pass and display it in the view? Should I set a separate message in the session for each type (e.g. Session::flash('message_danger', 'This is a nasty message! Something's wrong.');
)? Then I'd need a separate if statement for each message in my blade template.
任何建议表示赞赏.
推荐答案
一种解决方案是将两个变量闪存到会话中:
One solution would be to flash two variables into the session:
- 消息本身
- 警报的类别"
例如:
Session::flash('message', 'This is a message!');
Session::flash('alert-class', 'alert-danger');
那么在你看来:
@if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{ Session::get('message') }}</p>
@endif
请注意,我已将 默认值 放入 Session::获取()代码>.这样你只需要在警告应该是
alert-info
类以外的东西时覆盖它.
Note I've put a default value into the Session::get()
. that way you only need to override it if the warning should be something other than the alert-info
class.
(这是一个简单的例子,未经测试:))
这篇关于在 Laravel 中,在 session 中传递不同类型的 flash 消息的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!