2017-01-28 197 views
0

我正在嘗試關注此要點,以顯示Crud Rails應用程序https://gist.github.com/suryart/7418454的Bootstrap警報。其內容有代碼:Rails使用助手顯示Bootstrap警報

application_helper.rb:

模塊ApplicationHelper

def bootstrap_class_for flash_type 
    { success: "alert-success", error: "alert-danger", alert: "alert-warning", notice: "alert-info" }[flash_type] || flash_type.to_s 
    end 

    def flash_messages(opts = {}) 
    flash.each do |msg_type, message| 
     concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do 
       concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' }) 
       concat message 
      end) 
    end 
    nil 
    end 

application.html.erb

<body> 
    <div class="container"> 

     <%= flash_messages %> 

     <%= yield %> 
    </div><!-- /container --> 
</body> 

問題是我沒有看到任何的顯示消息。

我想,也許因爲要旨顯示返回零,也許我需要返回。每個迭代的內容,所以我做了這樣的事情在我的幫助返回的HTML:

def flash_messages 
    @flash_msg = "" 
    flash.each do |msg_type, message| 
     @flash_msg = concat(content_tag(:div, message, class: "alert #{bootstrap_class_for(msg_type)} fade in") do 
        concat content_tag(:button, 'x', class: "close", data: { dismiss: 'alert' }) 
        concat message 
        end) 
     puts "@flash_msg: #{@flash_msg}" 
    end 
    @flash_msg 
    end 

但是,當你查看打印語句的輸出它顯示我的頁面中輸入HTML,結束這實際上是我需要的HTML:

<div class="alert alert-info fade in"><button class="close" data-dismiss="alert">x</button>Signed in successfully.</div> 

我如何獲得這這樣的工作,它只返回最後一部分而不是整個頁面?

回答

1

您應該使用非輸出代碼塊:<% flash_messages %>(不是<%=)以及您的要點的原始代碼。

concat負責在模板上下文中注入html標記,幫助器的返回值沒有意義。