0

我有一个带有两个模板的网站用javascript触发的Rails flash消息

一个模板句柄定期接收Flash消息。 其他模板需要通过JavaScript解雇的消息:

var notyfy = notyfy(
{ 
    text: 'Hello I am an error', 
    type: 'error' // alert|error|success 
}); 

我有建立一个flash_helper。这个助手手表哪个模板是活动的,应发回正确的“闪信”:

  • 我不知道如何view_helper

这里内发送的JavaScript是我flash_helper.rb

# called via <%= flash_messages %> 

module FlashHelper 

    def flash_messages 
    return if flash.empty? 

    if controller.send(:_layout) == "pro/application" 
     flash.collect do |type, message| 
     # HERE SHOULD THE MAGICK HAPPEN :-) 
     javascript_tag "alert('All is good')", defer: 'defer' 
     end 
    else 
     flash.collect do |type, message| 
     content_tag(:div, :class => "notification-box notification-box-#{type}") do 
      content_tag(:p) do 
      content_tag(:i, nil, class: "icon-ok") + 
       message 
      end + 
       link_to("#", class: "notification-close notification-close-#{type}") do 
       content_tag(:i, nil, class: "icon-remove") 
       end 
     end 
     end.join("\n").html_safe 
    end 
    end 
end 

我的结果总是一个纯文本:

["<script defer=\"defer\" type=\"text/javascript\">\n//<![CDATA[\nalert('All is good')\n//]]>\n</script>", "<script defer=\"defer\" type=\"text/javascript\">\n//<![CDATA[\nalert('All is good')\n//]]>\n</script>", "<script defer=\"defer\" type=\"text/javascript\">\n//<![CDATA[\nalert('All is good')\n//]]>\n</script>", "<script defer=\"defer\" type=\"text/javascript\">\n//<![CDATA[\nalert('All is good')\n//]]>\n</script>"]

回答

0

我懂了它与raw

if controller.send(:_layout) == "pro/application" 
    html = "<script>" 
    flash.collect.with_index do |(type, message), i| 
    html += "var notyfy#{i} = notyfy({" 
    html += "text: '#{message}'," 
    html += "type: '#{type}'" 
    html += "});" 
    end 
    html += "</script>" 
    return raw(html) 
else 
.... 
... 
..