Rails Devise I18n Flash Messages with Twitter Bootstrap

后端 未结 6 677
轻奢々
轻奢々 2020-12-23 23:47

Hello I am new to ruby on rails and I am struggling to understand I18n\'s flash messages. I am using devise, rails 4, and twitter bootstrap.I understand that devise only use

6条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-24 00:31

    I made a wiki page within the devise wiki on github for How To: Integrate I18n Flash Messages with Devise and Bootstrap

    Flash Messages For the Site

    First we will make a rendered view to make the code concise. Within "app/views/layouts/application.html.erb" I added <%= render 'layouts/messages' %>.

    My file looks like:

    
      <%= render 'layouts/header' %>
      
    <%= render 'layouts/messages' %> <%= yield %> <%= render 'layouts/footer' %>

    Next we have to make the messages file. Make a new file in "app/views/layouts/_messages.html.erb" and add:

    <% flash.each do |key, value| %>
      
    ×
    • <%= value %>
    <% end %>

    This will give us flash messages for the entire site.

    Flash Messages For Devise

    For devise you need to override the way devise handles flash messages. Create a file called devise_helper in "app/helpers/devise_helper.rb".

    Inside the file you have to create a method called devise_error_messages!, which is the name of the file that tells devise how to handle flash messages.

    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
        
    #{messages}
    HTML html.html_safe end end

    Next in your devise views you will have to define where you want the error messages to appear. You will need to enter <%= devise_error_messages! %> within the devise pages. An example is entering this within "app/views/devise/registrations/.new.html.erb" (The sign up page)

    It should already be within the file, but you can move the code around to customize where it is shown.

    CSS For Flash Messages

    If you do not want to use the odd blue and yellow alerts that come default, I have set error and alert to have the same colorand success and notice to have the same color. I am using red for errors and alerts, and green for success and notice.

    Within my "app/assets/stylesheets/custom.css.scss" I have:

    /*flash*/
    .alert-error {
        background-color: #f2dede;
        border-color: #eed3d7;
        color: #b94a48;
        text-align: left;
     }
    
    .alert-alert {
        background-color: #f2dede;
        border-color: #eed3d7;
        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;
     }
    

提交回复
热议问题