干净的方法来设计实体吐司中的通知/警报

时间:2016-02-11 21:40:05

标签: javascript ruby-on-rails devise erb materialize

我在我的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 %>

任何人都可以提供更干净/更干的解决方案吗?感觉有点hacky。

4 个答案:

答案 0 :(得分:9)

桅杆不是&#34; hackyest&#34;方式,但仍然有点DRYer:

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

答案 1 :(得分:3)

我不认为我必须考虑这种技巧&#39; hacky&#39;。这在我的制作应用程序中适用于我:

<% 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(但如果有人认为他们有更好的解决方案,我会全力以赴)。

答案 2 :(得分:2)

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

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

答案 3 :(得分:0)

您可以将代码拆分为两部分。首先,在erb中将flash消息传递给js。其次,在脚本中触发toast。 看看https://github.com/leonid-shevtsov/unobtrusive_flash