简体   繁体   中英

Rails: How to loop through flash errors and flash notices separately?

I'm trying to style my flash errors (red background) differently from my flash notices (green background). However, I'm trying to do this in my layouts in my application.html.erb so that I can just take care of all of the flash all at once so there won't be any instance variables. However, I'm having trouble finding the right variable. This is my current application.html.erb:

<!DOCTYPE html>
<html>
<head>
  <title><%= complete_title(yield(:title)) %></title>
  <%= stylesheet_link_tag    "application", :media => "all" %>
  <%= javascript_include_tag "application" %>
  <%= csrf_meta_tags %>
</head>
<body class="clearfix">
    <div class="bigwrapper">


    <%= render 'layouts/header' %>

    #I want to figure out how to split this part up into flash[:notice].each and flash[:error].each so I can style them separately
    <% flash.each do |key, value| %>
        <%= content_tag(:div, value, class: "alert alert-#{key}") %>
    <% end %>

        <%= yield %>

    <%= render 'layouts/footer' %>
    </div>
</body>
</html>

Here is a sample sessions controller where I use flash[:error]

class SessionsController < ApplicationController

def new
end

def create
    user = User.find_by_email(params[:session][:email])
    if user && (!params[:session][:email].blank?) && user.authenticate(params[:session][:password])
    if params[:remember_me]
      cookies.permanent[:remember_token] = user.remember_token
    else
      cookies[:remember_token] = user.remember_token
    end
      sign_in user
      redirect_to user_path(user)
    else
      flash.now[:error] = "Invalid email and/or password."
      render 'new'
    end
end

def destroy
    sign_out
    redirect_to root_url
end

end

What exactly is the problem? You can already style them separately because you're building the flash divs with different class names depending on the flash type:

class: "alert alert-#{key}"

Just add some css:

.alert-error { background: red; }
.alert-notice { background: green; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM