2016-02-11 51 views
4

我在我的rails应用程序中使用设备,并作为标准配备noticealert在特定操作(例如用户登录)上呈现的方法。干净的方法来设计通知/警报实现烤面包

我也使用Materialize CSS框架,他们提供了一个很好的清洁'Toast' style notification。这是使noticealert与Toast一起工作的第一种方法。

<% if notice %> 
    <script type="text/javascript"> 
    Materialize.toast('<%= notice %>', 4000) 
    </script> 
<% end %> 
<% if alert %> 
    <script type="text/javascript"> 
    Materialize.toast('<%= alert %>', 4000) 
    </script> 
<% end %> 

任何人都可以提供更清洁/更干的解决方案吗?感觉有点哈克。

回答

6

它肥大是不是“hackyest”的方式,但还是有点干燥机:

<% flash.each do |message_type, message| %> 
    <%= javascript_tag "Materialize.toast('#{message}', 4000)" %> 
<% end %> 
3

我不认为我会认为这种技术'哈克'。这很适合我在我的生产应用程序:

<% flash.each do |type, message| %> 
    <% if type == "success" %> 
    <div class="alert alert-success alert-dismissable" role="alert"> 
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"> 
     <span aria-hidden="true">&times;</span> 
     </button> 
     <i class="icon-check"></i> 
     <p><%= message.html_safe %></p> 
    </div> 
    <% elsif type == "toast" %> 
    <script> 
     $(function() { 
     Materialize.toast("<%= message %>", 3000); 
     }); 
    </script> 
    <% else %> 
    <div class="alert alert-danger alert-dismissible" role="alert"> 
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"> 
     <span aria-hidden="true">&times;</span> 
     </button> 
     <i class="icon-notice"></i> 
     <%= message.html_safe %> 
    </div> 
    <% end %> 
<% end %> 

只是我认为在这里,但我看不出有什么不妥。底线是我认为没有一种方法可以让你的闪光灯触发js,而不是这样做(但是如果有人认为他们有更好的解决方案,我全都是耳朵)。

+0

这可能会更好。警告html非常相似。真的应该抽象成一个div。 – gregblass

+0

在:Materialize.toast('<%= message%>')中使用双引号......否则,如果邮件中有撇号,邮件将不会显示 – jpwynn

+0

Good all @jpwynn。已更新。 – gregblass

0

这里是我的解决方案。主要的代码只有两行。

<% unless flash.empty? %> 
    <script> 
     <% flash.each do |f| %> 
     <% type=f[0].to_s.gsub('alert', 'red').gsub('warning', 'orange').gsub('success', 'green') %> 
     Materialize.toast('<%= f[1] %>', 4000, '<%= type %>') 
     <% end %> 
    </script> 
<% end %>