我用render_to_string
和部分而不是助手来实现类似的东西。
# app/controller/dogs_controller.rb
def create
@dog = Dog.new(params[:dog])
@messages=[]
if @dog.save
@messages << "one"
@messages << "two"
flash[:notice] = render_to_string(:partial => "bulleted_flash")
redirect_to(dogs_path)
else
render :action => 'new
end
end
然后我格式化闪存信息的阵列中的一个HTML列表
# app/views/dogs/_bulleted_flash.html.erb
<ol>
<% @messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ol>
如果需要继续使用一个助手,那么我想你将会产生以下HTML
# http://0.0.0.0:3000/dogs
<body>
<div id="flash_notice">
<ul>
<li>one</li>
<li>two</li>
</ul>
</div>
...
</body>
需要将html_safe
方法附加到字符串以防止它被编码(默认情况下为rails 3)。这是一个question showing how to use html_safe
in a similar fashion