当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby on rails - Best practice method of displaying flash messages

问题描述:

I'm wondering what's the best practice for displaying flash messages. The two main ways I've seen are using something like this scaffold generated code

<p id="notice"><%= notice %></p>

or placing code like this in your application header.

<% if !flash.empty? %>

<div id="flash">

<% flash.keys.each do |k| %>

<div class="<%= k %>">

<%= flash[k] %>

</div>

<% end %>

</div>

It appears to me that the first method adds more flexibility while the latter improves code readability and eliminates redundancy. Is there a method most rails developers prefer? As a side question how does scaffolding implement notice? Is it just a helper that accesses the flash hash? Why go through the trouble of using the helper when you can directly use the flash hash? Thanks

网友答案:

I'm doing it this way:

<% flash.each do |key, value| %>
  <%= content_tag :div, value, class: "flash #{key}" %>
<% end %>
网友答案:

Calling a partial keeps your application.html.erb even cleaner..

<%= render 'shared/flash_messages' if !flash.empty? %>

.. and in the partial do something like what @zolter mentioned:

<div id="flash_messages">
  <% flash.each do |key, value| %>
    <%= content_tag(:div, value, :class => "flash #{key}") %>
  <% end %>
</div>
网友答案:

Why not put the second method on a helper function so it doesn't affect code readability on layouts?

分享给朋友:
您可能感兴趣的文章:
随机阅读: