Skip to content

Instantly share code, notes, and snippets.

@fjahr
Forked from suryart/application.html.erb
Last active October 4, 2021 10:35
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save fjahr/b3828b9f4e333e74ba1894687d65e055 to your computer and use it in GitHub Desktop.
Save fjahr/b3828b9f4e333e74ba1894687d65e055 to your computer and use it in GitHub Desktop.
Displaying Rails 5 flash messages with Twitter Bootstrap 4 (last tested on Alpha-v6). Updated version of https://gist.github.com/suryart/7418454
// layout file
<body>
<div class="container">
<%= flash_messages %>
<%= yield %>
</div><!-- /container -->
</body>
module ApplicationHelper
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
def flash_messages(opts = {})
flash.each do |msg_type, message|
concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)}", role: "alert") do
concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' })
concat message
end)
end
nil
end
end
@jhonnatas
Copy link

Thanks man!

@lorrenestacy
Copy link

amazing, thank you!

@AhmedKamal20
Copy link

  def bootstrap_class_for(flash_type)
    case flash_type.to_sym
    when :notice then "alert-info"
    when :success then "alert-success"
    when :error then "alert-danger"
    when :alert then "alert-danger"
    else "alert-#{flash_type}"
    end
  end

@GaganGupta19
Copy link

@AhmedKamal20 No need to use cases when you can use hashes :) much cleaner approach!

@gudata
Copy link

gudata commented Dec 26, 2020

  def flash_messages()
    bootstrap_class_for = {
      success: "alert-success",
      error: "alert-danger",
      alert: "alert-warning",
      notice: "alert-info"
    }.stringify_keys


    output_html = "".html_safe
    flash.each do |flash_type, message|
      css_class = bootstrap_class_for[flash_type.to_s] || flash_type.to_s
      output_html += content_tag(:div, message, class: "alert #{css_class}", role: "alert") do
        content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' }) +
        message
      end
    end
    output_html
  end

@aqabawe
Copy link

aqabawe commented Jan 10, 2021

How can we add support to html in the flash body? for example adding a link.


Edit:
You can do that by replacing message with message.html_safe
Thanks for the very useful gist.

@johnhailu
Copy link

bootstrap 5

def flash_messages(opts = {})
flash.each do |msg_type, message|
concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} alert-dismissible fade show", role: "alert") do
concat content_tag(:button, '', class: "btn-close", data: { bs_dismiss: 'alert' })
concat message
end)
end
nil
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment