在Laravel中,是在会话中传递不同类型的Flash消息的最佳方法 [英] In Laravel, the best way to pass different types of flash messages in the session
问题描述
我正在Laravel中创建我的第一个应用程序,并且试图让我了解会话Flash消息.据我在控制器操作中所知,我可以通过以下方式设置即插即用消息
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::get()
中.这样,如果警告不是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中,是在会话中传递不同类型的Flash消息的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!