我们在application.rhtml(global layout)里经常需要写各种flash的显示:
[code]
<% unless flash[:notice].nil? %>
<div id="notice"><%= flash[:notice] %></div>
<% end %>
<% unless flash[:error].nil? %>
<div id="error"><%= flash[:error] %></div>
<% end %>
[/code]
我们可以循环来输出flash:
[code]
<% flash.each do |key, msg| %>
<%= content_tag :div, msg, :id => key %>
<% end %>
[/code]
这样写倒是节约了代码,但是可能flash消息的顺序不是很好,我们可以这样写:
[code]
<%- [:error, :warning, :notice, :message].each do |key| -%>
<%= content_tag :div, flash[key], :id=> key if flash[key] %>
<%- end -%>
[/code]
[code]
<% unless flash[:notice].nil? %>
<div id="notice"><%= flash[:notice] %></div>
<% end %>
<% unless flash[:error].nil? %>
<div id="error"><%= flash[:error] %></div>
<% end %>
[/code]
我们可以循环来输出flash:
[code]
<% flash.each do |key, msg| %>
<%= content_tag :div, msg, :id => key %>
<% end %>
[/code]
这样写倒是节约了代码,但是可能flash消息的顺序不是很好,我们可以这样写:
[code]
<%- [:error, :warning, :notice, :message].each do |key| -%>
<%= content_tag :div, flash[key], :id=> key if flash[key] %>
<%- end -%>
[/code]
本文介绍了一种优化Rails应用中Flash消息显示的方法。通过循环输出不同类型的Flash消息,并确保消息按预设顺序显示,提高了用户体验。文章提供了具体的Ruby on Rails代码示例。
1710

被折叠的 条评论
为什么被折叠?



