public
Last active

Rails flash messages using Twitter Bootstrap

  • Download Gist
_flash_messages.html.erb
HTML+ERB
1 2 3 4 5 6
<% flash.each do |type, message| %>
<div class="alert <%= bootstrap_class_for(type) %> fade in">
<button class="close" data-dismiss="alert">×</button>
<%= message %>
</div>
<% end %>
application.html.erb
HTML+ERB
1
<%= render partial: "shared/flash_messages", flash: flash %>
application_helper.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
module ApplicationHelper
 
def bootstrap_class_for flash_type
case flash_type
when :success
"alert-success"
when :error
"alert-error"
when :alert
"alert-block"
when :notice
"alert-info"
else
flash_type.to_s
end
end
 
end

Why not just using Hash for #bootstrap_class_for ?

{success: 'alert-success',...}[flash_type] || flash_type.to_s

this worked well, thanks!

Which version of Bootstrap is this for? I installed it on BS3 and it won't clear when the "X" is clicked.

Hi, I think there is an issue with Rails 4. May be caused for Turbolinks use?

Nice , it worked for me Rails 4. Thanks

Great ! It worked with rails4.

Great ! It worked with rails4.

Nice one, I've created another version of this here: https://gist.github.com/suryart/7418454

Great, fixed some problems with flash messages in ruby.railstutorial.org (with Rails 4 and las bootstrap). Thank you.

If you are using Bootstrap 3, the class names have been changed. Here is the new mapping:

module ApplicationHelper

  def bootstrap_class_for flash_type
    case flash_type
      when :success
        "alert-success" # Green
      when :error
        "alert-danger" # Red
      when :alert
        "alert-warning" # Yellow
      when :notice
        "alert-info" # Blue
      else
        flash_type.to_s
    end
  end

end

In file _messages.html.erb you can simply put

<% flash.each do |type, message| %>
  <div class="alert <%= bootstrap_class_for(type) %> alert-dismissable fade in">
    <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
    <%= message %>
  </div>
<% end %>

does this work with GEM --- https://github.com/seyhunak/twitter-bootstrap-rails . I can't get success error message to show. any ideas?

RE: success message not working.... what is strange is the other 3 do work.

FYI - to get this to work, i also needed to add: add_flash_types :success, :info, :warning, :danger
to the applications controller.

As of 4.1 this code needs to be updated due to the :symbol to String change in flash messages.

  def bootstrap_class_for(flash_type)
    case flash_type
      when "success"
        "alert-success"   # Green
      when "error"
        "alert-danger"    # Red
      when "alert"
        "alert-warning"   # Yellow
      when "notice"
        "alert-info"      # Blue
      else
        flash_type.to_s
    end
  end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.