I'm using devise in my rails app and as standard it comes with notice
and alert
methods which render on specific actions (e.g. a user signing in).
I am also using the Materialize CSS framework and they provide a nice clean 'Toast' style notification. This is the first approach at making notice
and alert
work with 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 %>
Can anyone provide a cleaner/more DRY solution? Feels a little hacky.
It mast be not the "hackyest" way, but still a bit DRYer:
<% flash.each do |message_type, message| %> <%= javascript_tag "Materialize.toast('#{message}', 4000)" %> <% end %>
I don't think I'd necessarily consider that technique 'hacky'. This works well for me in my production app:
<% 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">×</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">×</span>
</button>
<i class="icon-notice"></i>
<%= message.html_safe %>
</div>
<% end %>
<% end %>
Just my opinion here, but I don't see anything wrong with that.
Bottom line is I don't think there is a way out of the box to have your flash trigger js other than doing it this way (but I'm all ears if someone thinks they have a better solution).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With