我仍然在我的 rails 4 演示网站上工作,我看到一个奇怪的事情。
format.html { redirect_to @widget, notice: 'Widget was successfully created.' }
这将在重定向的页面中呈现 flash 消息,这是预期的。但是,附加到消息 div 的 css 类是alert alert-notice
,而不是有效的 Bootstrap 警报类,如alert-info
。
在哪里被设置为这个闪存的类,以及如何自定义它?
另外,如果我通过 Ajax 删除记录,有没有办法访问核心闪存容器通过 js 显示消息,或者我必须显示 / 隐藏我自己的 Flash 消息 div 只是 Ajax 请求?
编辑:我的迈克尔 · 哈特尔的灵感layouts/application.html.erb
:
<div class="container">
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
<%= yield %>
</div>
谢谢
编辑2:
也许我在我原来的问题中不够清楚。在这种情况下,我确切地理解了类是如何在 flash 对象中设置的。我有兴趣学习如何使用和自定义format.html
块中的notice:
。似乎应该有一种通过此通知传递类的方或者这不是核心 Rails 的做事方式?
在application.html.erb
中,您将显示flash
消息。
更新代码如下
<% flash.each do |name, msg| %>
<%= content_tag :div, msg, class: "alert alert-info" %>
<% end %>
您可以在class
选项中添加要应用于 flash 消息的类。
类设置为alert alert-notice
,因为代码中有alert alert-<%= key %>
。当您调用redirect_to @widget, notice: 'Widget was successfully created.
闪存消息将被添加到flash
哈希中,密钥为notice
,值为Widget was successfully created.
,即
flash[:notice] = "Widget was successfully created."
EDIT #2
format.html { redirect_to @widget,notice:'Widget was successfully created.' }
notice: 'Widget was successfully created.'
是传递给redirect_to
方法的参数。它被添加到此方法中的flash
哈希中。
将此添加到
app / controllers / application_controller.rb
class ApplicationController
add_flash_types :success, :warning, :danger, :info
end
然后你可以在你的控制器
format.html { redirect_to @widget, success: 'Widget was successfully created.' }
前提是你在你的布局中做到了这一点
<div class="container">
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
<%= yield %>
</div>
如果你不想搞砸你的ApplicationController
作为 @ Sachin Mour 表示,你可以添加一些额外的 CSS 类,相应地:
app/assets/stylesheets/custom.scss
:
/*flash*/
.alert-error {
background-color: #f2dede;
border-color: #eed7;
color: #b94a48;
text-align: left;
}
.alert-alert {
background-color: #f2dede;
border-color: #eed7;
color: #b94a48;
text-align: left;
}
.alert-success {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #468847;
text-align: left;
}
.alert-notice {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #468847;
text-align: left;
}
一步一步的教程,如何使用 devise 和 bootstrap 处理 flash 消息,您可以找到here
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(1条)