How to define Flash Notifications with Twitter Bootstrap Rails gem

我们两清 提交于 2019-12-02 20:51:05

You're using the flash helper from seyhunak's twitter-bootstrap-rails gem. Instead of using the helper, you can set up the code yourself and see how everything works.

Here's how I set up Rails flash messages with Twitter Boostrap.

Rails uses :notice and :alert as flash message keys. Twitter Bootstrap provides a base class .alert with additional classes .alert-success and .alert-error (see the Bootstrap documentation on alerts). A bit of parsing is required to get a Rails “notice” message to be styled with the Twitter Bootstrap “alert-success” style. Any other message, including a Rails “alert” message, will be styled with the Twitter Bootstrap “alert-error” style.

By default, Twitter Bootstrap applies a green background to .alert-success and a red background to .alert-error. Twitter Bootstrap provides a third class .alert-info with a blue background. With a little hacking, it’s possible to create a Rails flash message with a custom name, such as :info, that will display with the Bootstrap .alert-info class. However, it’s wise to stick with the Rails convention of using only “alert” and “notice.” Earlier versions of Rails used "error" but the current practice is to use "alert" instead of "error."

You can include code to display flash messages directly in your application layout file or you can create a partial. Here's an example with a partial.

First, what goes in the application layout:

# app/views/layouts/application.html.erb 
.
.
.
<%= render 'layouts/messages' %>
.
.
.

Next, the partial that gets included in the application layout:

# app/views/layouts/_messages.html.erb
# Rails flash messages styled for Bootstrap 3.0
# works with Rails 4.0 or Rails 4.1
<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name.to_s == 'notice' ? 'success' : 'danger' %>">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

And an example of setting two different flash messages in a controller:

class VisitorsController < ApplicationController

  def new
    flash[:notice] = 'Welcome!'
    flash[:alert] = 'My birthday is soon.'
  end

end

This example comes from an in-depth article I wrote:

Twitter Bootstrap and Rails

For an alternative that accommodates four different flash message types (success, error, alert, notice), see an example of Rails Flash Messages using Twitter Bootstrap.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!