简体   繁体   中英

How can I render more than one flash message?

In my application I want to generate sometimes more than one flash message. I have the following method in my application_helper.rb

  def flash_message
    flash.each do |key, msg|
      return render "admin/shared/#{key}", msg: msg 
    end
  end

But when I initialize a few flash messages in my controller, it shows only the first. Any ideas?

Edit:

And in my layout I do something like that

- unless flash.empty?
   = flash_message

As per your code it will return only fist one of the list..

I think its better to do this in view

using View:

- Ruby Code in View 
%ul#error-msg-list
  flash.each do |key, msg|
    %li.error-message= "<!-- your html --> admin/shared/#{key}" 
  end

Or else you can store all the flash messages in another array.. and do your logic at controller level, but this is unnecessary memory cost.

Your function will return on the first call to return .

I guess you're aiming for something like...

  def flash_message
    result = ''
    flash.each do |key, msg|
      result += render("admin/shared/#{key}", msg: msg) 
    end
    result
  end

But if I'm not mistaken you will also need to pass the arguments to render differently. Try:

render(partial: "admin/shared/#{key}", locals: { msg: msg })

A combined version, with a functional twist using map and join will look like this:

  def flash_message
    flash.map do |key, msg|
      render(partial: "admin/shared/#{key}", locals: { msg: msg })
    end.join('')
  end

EDIT:

Here is an example. If your flash looks like this:

flash = {notice: 'Everything find.', error: 'Ups, my bad: Error'}

This code

flash.map { |key, str| "<div class='#{key}'>#{str}</div>" }.join('')

will give you this

"<div class='notice'>Everything find.</div><div class='error'>Ups, my bad: Error</div>"

If this only renders one flash message, I assume there is only one message in flash . Maybe you've overwritten the first, while setting the latter?

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