【问题标题】:How to define Flash Notifications with Twitter Bootstrap Rails gem如何使用 Twitter Bootstrap Rails gem 定义 Flash 通知
【发布时间】:2013-07-29 18:29:51
【问题描述】:

我正在尝试在控制器中设置 Flash 通知,但似乎我只能定义 :notice。当我尝试定义 :errors 或 flash[:errors] 时,我遇到了一堆错误。我目前正在使用此功能,但所有消息显然都是通知类型,而不是错误或警告。我想知道如何设置错误或警告而不是通知。我正在使用 rails 3.2 和 twitter bootstrap rails gem

在 application.html.erb 中

<%= bootstrap_flash %>

manuals_controller.rb

class ManualsController < ApplicationController
  def create
    respond_to do |format|
      format.html { redirect_to root_url, notice:'MyManual was successfully created.' }
    end
  end
end

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3 twitter-bootstrap flash-message


【解决方案1】:

您正在使用 seyhunak 的 twitter-bootstrap-rails gem 中的 flash 助手。您可以自己设置代码并查看一切如何工作,而不是使用帮助程序。

以下是我使用 Twitter Boostrap 设置 Rails 闪存消息的方法。

Rails 使用 :notice 和 :alert 作为 flash 消息键。 Twitter Bootstrap 提供了一个基类 .alert 以及附加类 .alert-success 和 .alert-error(请参阅关于警报的 Bootstrap 文档)。需要进行一些解析才能获得使用 Twitter Bootstrap “alert-success” 样式设置样式的 Rails “通知”消息。任何其他消息,包括 Rails “警报”消息,都将使用 Twitter Bootstrap “警报错误”样式。

默认情况下,Twitter Bootstrap 为 .alert-success 应用绿色背景,为 .alert-error 应用红色背景。 Twitter Bootstrap 提供了蓝色背景的第三类 .alert-info。稍加修改,就可以创建一个带有自定义名称的 Rails flash 消息,例如 :info,它将与 Bootstrap .alert-info 类一起显示。然而,明智的做法是遵守 Rails 的约定,即只使用“alert”和“notice”。早期版本的 Rails 使用“错误”,但目前的做法是使用“警报”而不是“错误”。

您可以在应用程序布局文件中包含直接显示 Flash 消息的代码,也可以创建部分代码。这是一个带有部分的示例。

首先,应用程序布局:

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

接下来,包含在应用程序布局中的部分:

# 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 %>

以及在控制器中设置两个不同的闪存消息的示例:

class VisitorsController < ApplicationController

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

end

这个例子来自我写的一篇深度文章:

Twitter Bootstrap and Rails

有关适应四种不同闪存消息类型(成功、错误、警报、通知)的替代方案,请参阅Rails Flash Messages using Twitter Bootstrap 的示例。

【讨论】:

  • 当我进行上述更改时,我收到一个错误“无法将符号转换为字符串”。感谢您彻底解释您的初步答案。
  • 这是我在 GitHub 上的 Rails Bootstrap 示例应用程序的链接,其中包含 Flash 消息代码。克隆示例并将其作为参考实现进行检查可能会有所帮助。
  • 应该可能是“危险”而不是“错误”,因为 alert-error 不是引导类
  • 道格,感谢您指出这一点。我已经更新了 Bootstrap 3.0 的代码,它适用于 Rails 4.0 或 Rails 4.1。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2013-12-12
  • 2013-09-26
  • 2012-05-31
相关资源
最近更新 更多