'Bootstrap/Rails - Adding 'close' to flash notice
i've been trying to work this out myself and not have to ask but I can't seem to find a solution.
I have a flash notice working perfectly in my app: application.html.erb excerpt:
<body>
<div class="container">
<% flash.each do |key, value| %>
<%= content_tag :div, value, class: "alert alert-#{key}" %>
<% end %>
<%= yield %>
</div>
</body>
..my question is, is there a way of adding the 'close' bootstrap feature within the above code?..
i.e:
<div class="alert alert-warning alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>
..but including it within my <%= %>
(it obviously doesn't need to be the 'warning' class as above, this was just copied from bootstrap as an example)
Thanks in advance!!
Justin
@MattBricston ..i'm struggling to grasp the key == :notice ? 'success' : 'danger' line, would it only work for 'success', and 'danger' bootstrap alerts?..is it just a matter or adding : 'warning' : 'info' etc??...
Thanks again, really appreciate it :)
Solution 1:[1]
I'm using Bootstrap 4.0. Add this to your application layout right before the <%= yield%>
<% if flash[:notice] %>
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:notice]%>
</div>
<% elsif flash[:error]%>
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:error]%>
</div>
<% elsif flash[:alert] %>
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
<%= flash[:alert]%>
</div>
<% end %>
Solution 2:[2]
As per Bootstrap 5
In application_helper.rb | _notices.html.erb is in the comment below
def bootstrap_class_for(flash_type)
{
success: "alert-success",
error: "alert-danger",
alert: "alert-warning",
notice: "alert-info"
}.stringify_keys[flash_type.to_s] || flash_type.to_s
end
Solution 3:[3]
<div class="alert alert-info">
<span class="glyphicon glyphicon-info-sign"> </span>
<strong> Sorry....! </strong> Something went wrong.
<button type="button" class="close" data-dismiss="alert"> × </button>
</div>
This worked for me.... Please try it once.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Arthur |
