简体   繁体   English

如何呈现多个即插即用消息?

[英]How can I render more than one flash message?

In my application I want to generate sometimes more than one flash message. 在我的应用程序中,我有时会生成不只一个Flash消息。 I have the following method in my application_helper.rb 我的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 . 您的函数将在第一次调用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. 但是,如果我没记错的话,您还需要传递参数以进行不同的render Try: 尝试:

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

A combined version, with a functional twist using map and join will look like this: 结合在一起的版本,具有使用mapjoin的功能性扭曲,如下所示:

  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看起来像这样:

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 . 如果这只是一个呈现提示信息,我认为只有一个在消息flash Maybe you've overwritten the first, while setting the latter? 也许您在设置第一个时覆盖了第一个?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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