Rails 4 - Toaster notifications rather than flash notifications

后端 未结 1 1857
面向向阳花
面向向阳花 2021-02-10 07:44

I am using this library, (https://github.com/CodeSeven/toastr) and I am trying to push my Flash notifications to the javascript function Toastr has provided for me. How do I cal

相关标签:
1条回答
  • 2021-02-10 08:26

    What I'd recommend is to make a new flash type for this sort of thing and then render that as JS in your layout.

    ApplicationController
    
    def toast(type, text)
      flash[:toastr] = { type => text }
    end
    
    
    app/views/layouts/<your layout>.html.erb
    # (or in a partial to be reused in various layouts)
    # the <script> tag isn't needed if code snippet is
    # included in an existing script block, of course.
    
    <% if flash[:toastr] %>
      <script type="text/javascript">
        <% flash[:toastr].each do |type, message| %>
          toastr.<%= type %>(<%= message.inspect %>)
        <% end %>
      </script>
    <% end %>
    

    So this way you get all the standard behavior you're used to from the flash object and you get easy to understand javascript written in your views directly via erb. You may need to add an options hash to the ApplicationController#toast method so you can do a flash.now[:toastr] at times, of course. And so on... But this should get you started.

    0 讨论(0)
提交回复
热议问题