Ruby-on-rails 显示快闪消息的最佳实践方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9390778/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:52:39  来源:igfitidea点击:

Best practice method of displaying flash messages

ruby-on-railsruby-on-rails-3

提问by Steve

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

我想知道显示 Flash 消息的最佳做法是什么。我见过的两种主要方法是使用类似这种脚手架生成的代码

<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>
<% end %>

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

在我看来,第一种方法增加了更多的灵活性,而后者提高了代码的可读性并消除了冗余。有没有大多数 Rails 开发人员更喜欢的方法?作为一个附带问题,脚手架如何实施通知?它只是访问闪存哈希的助手吗?当您可以直接使用闪存哈希时,为什么还要麻烦使用助手?谢谢

回答by zolter

I'm doing it this way:

我是这样做的:

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

回答by user664833

Calling a partial keeps your application.html.erbeven cleaner..

调用部分可以让你application.html.erb更干净..

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

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

..并在部分做一些@zolter提到的事情:

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

回答by fjyaniez

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

为什么不将第二种方法放在辅助函数上,这样它就不会影响布局上的代码可读性?

回答by ümit ?ztürk

<% if flash[:notice] %>
  <div class="notification is-primary global-notification">
    <p class="notice"><%= notice %></p>
  </div>
<% end %>

<% if flash[:alert] %>
  <div class="notification is-danger global-notification">
    <p class="alert"><%= alert %></p>
  </div>
<% end %>