我对 Bootstrap 2.0 的回答始于 @Railslerner 的有用答案,但在部分中使用了不同的代码。
应用程序/helpers/application_helper.rb(与@Railslerner的答案相同)
module ApplicationHelper
def flash_class(level)
case level.to_sym
when :notice then "alert alert-info"
when :success then "alert alert-success"
when :error then "alert alert-error"
when :alert then "alert alert-error"
end
end
end
某处在应用程序/视图/布局/application.html.erb:
<%= render 'layouts/flash_messages' %>
应用程序/视图/布局/_flash_messages.html.erb
<div>
<% flash.each do |key, value| %>
<div class="<%= flash_class(key) %> fade in">
<a href="#" data-dismiss="alert" class="close">×</a>
<%= value %>
</div>
<% end %>
</div>
差异:
- 每次调用时不会循环遍历不同的错误级别。
- 相反,如果哈希值包含消息(遵循Michael Hartl 的 Rails 教程中的方法 http://ruby.railstutorial.org/book/ruby-on-rails-tutorial#sec:the_flash).
- 不使用
<p>
tag, 不再需要 http://twitter.github.com/bootstrap/components.html#alerts在 Bootstrap 2.0 中。
请记住包含 bootstrap-alert.js,以便淡入淡出和关闭功能正常工作。如果您使用 bootstap-sass gem,请将此行添加到应用程序/资产/javascripts/application.js:
//= require bootstrap-alert
Update 8/9/2012: Folders updated. I actually put everything except the helper under
app/views/layouts since
flash_messages
is only used in
app/views/layouts/application.html.erb.
2015 年 6 月 5 日更新:更新到 Rails 4.2 后,我发现level
(至少有时)作为字符串传入并且无法匹配 ApplicationHelper 中的 case 语句。将其更改为level.to_sym
.