在Materialize Toast中设计通知/警报的简洁方法

6
我在我的Rails应用程序中使用devise,作为标准功能,它带有noticealert方法,这些方法会在特定的操作(例如用户登录)上呈现。
我还使用Materialize CSS框架,他们提供了一个漂亮干净的'Toast'风格通知。这是将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 %>

有没有人能提供更简洁/更符合DRY原则的解决方案?感觉有点不太正式。
4个回答

10

这可能不是最“hacky”的方法,但仍然更加DRY:

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

3

我不认为这种技术是“hacky”的。在我的生产应用中,这种方法效果很好:

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

这只是我的个人观点,但我认为这没有任何问题。

最重要的是,我认为除了这种方法,没有其他方式可以让您的flash触发js(但如果有人认为他们有更好的解决方案,我很愿意听取)。


这个可以改进。警告HTML非常相似。应该抽象成一个div。 - Greg Blass
请使用双引号在 Materialize.toast('<%= message %>' ... 中,否则如果消息中有撇号,则消息将无法显示。 - jpw
大家好@jpwynn。已更新。 - Greg Blass

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

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接