如何在Rails 4中将content_tag与嵌套块一起使用?

时间:2015-12-06 05:50:19

标签: ruby-on-rails erb

由于某种原因,这不起作用。如何使用content_tag的块,如文档所示?

<% 
flash.each do |name, msg|
  if msg.is_a? Array
    concat content_tag(:div, :id => "flash_#{name}", class: 'alert bg-'+{'notice'=>'success', 'alert'=>'danger', 'error'=>'danger'}[name].to_s) do
      msg.each do |m|
        concat m
        concat "<br>".html_safe
      end
    end
  else
    concat content_tag :div, msg, :id => "flash_#{name}", class: 'alert bg-'+{'notice'=>'success', 'alert'=>'danger', 'error'=>'danger'}[name].to_s
  end
end 
%>

Documentation for content_tag

<%= content_tag :div, class: "strong" do -%>
  Hello world!
<% end -%>
 # => <div class="strong">Hello world!</div>

我的输出:

<div>{:id=&gt;"flash_alert", :class=&gt;"alert bg-danger"}</div>

控制器中设置闪光灯的线路:

  flash.alert = @tracking.errors.full_messages

1 个答案:

答案 0 :(得分:1)

我在这里找到答案:Rails' concat method and blocks with do...end doesn't work

该块已传递到concat,而不是content_tag。这很有效:

concat content_tag(:div, :id => "flash_#{name}", class: 'alert bg-'+{'notice'=>'success', 'alert'=>'danger', 'error'=>'danger'}[name].to_s) {
  msg.each do |m|
    concat m
    concat "<br>".html_safe
  end
}