2017-02-26 73 views
0

我使用railsmaterialize toasts顯示閃光燈消息。這裏是代碼我使用顯示烤架中每個閃光燈的不同烤麪包機

<% unless flash.empty? %> 
    <script> 
     <% flash.each do |f| %> 
     <% type=f[0].to_s.gsub('alert', 'red').gsub('warning', 'deep-purple').gsub('success', 'green') %> 
     Materialize.toast('<%= f[1] %>', 4000, '<%= type %>') 
     <% end %> 
    </script> 
<% end %> 

的問題是,這不會splitflash messagesdifferent toasts,而不是顯示所有在single toast。我怎樣才能讓每個flash顯示在它自己的toast

回答

1

閃爍重新組合在類型/值的散列中。我建議你創建一個幫手來包裝閃爍的演示文稿標籤

flash的值很可能是單個字符串或數組或字符串。我個人使用閃光燈周圍的包裝,讓我推我想要的相同類型的閃光燈

下面的代碼處理字符串或數組閃爍。注意flash.each do |type, content|

def flashes 
    content_tag(:div, class: 'flash-group') do 
    flash.each do |type, content| 
     if content.respond_to?(:each) 
     # If you have an array of flashes, regroup them under the same "flash" block 
     concat(single_flash(type, flash) do 
      # The flash messages are added as a list 
      content_tag(:ul) do 
      content.flatten.each do |message| 
       msg = if message.respond_to?(:html_safe) 
       message.html_safe 
       else 
       msg 
       end 
       concat(content_tag(:li, msg)) 
      end 
      end 
     end) 
     else 
     concat(single_flash(type, content.html_safe)) 
     end 
    end 
    end 
end 

此包裝是有點兒框架無關,你可以定義single_flash不過你想要的,只是用<%= flashes %>在佈局中。

爲你的材料實現你必須像

def single_flash(type, content = nil) 
    type_class = case type 
    when 'alert' 
    'red' 
    when 'warning' 
    'deep-purple' 
    when 'success' 
    'green' 
    else 
    '?' 
    end 
    Materialize.toast(content, 4000, type_class) 
end 

比如我舉實施

# Render a single flash, styles according to the flash type 
    def single_flash(type, content = nil) 
    alert_class = ['alert alert-dismissible media'] 
    contextual_class = case type.to_sym 
    when :alert, :danger, :error, :fatal 
     'danger' 
    when :warning, :todo 
     'warning' 
    when :notice, :success 
     'success' 
    else 
     'info' 
    end 
    alert_class << "alert-#{contextual_class}" 
    close_class = "close text-#{contextual_class}" 
    content_tag(:div, class: alert_class, role: 'alert') do 
     concat(content_tag(:div, class: 'flash-icon media-left media-middle') do 
     font_awesome(case type.to_sym 
     when :fatal, :error 
      'exclamation-triangle' 
     when :danger, :warning 
      'exclamation-triangle' 
     when :success 
      'check' 
     when :notice, :info 
      'info-circle' 
     else 
      'question' 
     end) 
     end) 
     concat(content_tag(:div, class: 'flash-message media-body') do 
     block_given? ? yield : simple_format(content) 
     end) 
     concat(content_tag(:div, class: 'media-right media-middle') do 
     concat(content_tag(:button, class: close_class, 'data-dismiss': 'alert') do 
      concat(content_tag(:span, aria_hidden: true) {'&times;'.html_safe }) 
      concat(content_tag(:span, class: 'sr-only') { 'Close' }) 
     end) 
     end) 
    end 
    end