How to apply customized Bootstrap messages errors

2019-06-03 04:36发布

问题:

I'm applying Bootstrap3 errors style to all messages in my Rails4 app, here (source)

def bootstrap_class_for flash_type
    { success: "alert-success", error: "alert-error", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s
  end

  def flash_messages(opts = {})
    capture do
      flash.each do |msg_type, message|
        concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do 
          concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' })
          concat message 
        end)
      end
      nil
    end
  end

In the same time I'm trying to apply same style to Devise error messages but it does not work. For example; within [views/devise/registration/new] you see <%= devise_error_messages! %> which it shows error messages without style.

How could I apply Bootstrap style (above) to devises error messages?

回答1:

Override the devise_error_messages! helper method

app/helpers/devise_helper.rb

module DeviseHelper
 def devise_error_messages!
   return "" if resource.errors.empty?
   messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
   html = <<-HTML
     <div class="alert alert-error alert-block">
       #{messages}
     </div>
    HTML
  html.html_safe
end

Where the devise doesn't used any css class so we use alert-error class instead you can use your custom class

<div class="alert #{boostrap_class_for(:error)} alert-block">