Custom Classes and Formatting on Flash Messages for Twitter Bootstrap defaults

ruby-on-rails, ruby-on-rails-3, twitter-bootstrap

Solution

My answer for Bootstrap 2.0 starts from the helpful answer by @Railslerner but uses different code in the partial.

app/helpers/application_helper.rb (same as @Railslerner's answer)

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

Somewhere in app/views/layouts/application.html.erb:

<%= render 'layouts/flash_messages' %>

app/views/layouts/_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>

Differences:

- Does not loop through different error levels each time it is called.

- Instead loops through the flash hash if the hash contains messages (following the approach in Michael Hartl's Rails Tutorial).

- Does not use the `<p>` tag, no longer required in Bootstrap 2.0.

Remember to include bootstrap-alert.js so the fade and close functionality will work. If you're using the bootstap-sass gem, add this line to app/assets/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.

Update 6/5/2015: After updating to Rails 4.2, I discovered that `level` was (at least sometimes) coming in as a String and failing to match the case statement in the ApplicationHelper. Changed that to `level.to_sym`.

Problem

I am integrating twitter bootstrap css into my application. Going along just fine,but I don't know how to customize the css and wrappers for my flash messages. I would like my flash messages to be formatted with the default Bootstrap classes: ``` <div class="alert-message error"> <a class="close" href="#">×</a> <p><strong>Oh snap!</strong> Change this and that and <a href="#">try again</a>.</p> </div> ``` Currently I output my flash messages with: ``` <% flash.each do |name, msg| %> <%= content_tag :div, msg, :id => "flash_#{name}" %> <% end %> ``` Is there an easy way to run a little switch that would make :notification or other rails flash messages map to the classes in bootcamp, like info?

Original source