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?
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:
<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
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With