简体   繁体   中英

How do you add toastr-rails gem to Rails 6 project?

I am trying to add the toastr gem to my Rails 6 project. I also have the devise gem installed.

I do not understand webpacker and how to make toastr-rails webpacker friendly.

I have read all the documentation. Don't tell me to read the documentation.

This is what I've tried:

yarn add toastr

Then in my assets/packs/application.js file, I added:

@import 'toastr'

And in my assets/stylesheets/application.scss file, I added:

*= require_toastr

Finally my layouts/application.html.erb has this code:

<!DOCTYPE html>
<html>
 <head>
 </head>
 <body>
  <% unless flash.empty? %>
    <script type="text/javascript">
        <% flash.each do |f| %>
        <% type = f[0].to_s %>
        toastr['<%= type %>']('<%= f[1] %>');
        <% end %>
    </script>
  <% end %>
  <%= yield %>
 </body>
</html>

I don't get the toast notifications. I don't get any notifications. But this code works on my Rails 4 project.

If you want to add toastr with toastr-rails gem, use asset pipeline instead of webpack.

Here are the steps to add toastr with the webpack .

  1. Add toastr js with yarn

     yarn add toastr
  2. Require toastr in app/javascript/packs/application.js . I added it to the global to avoid errors

    global.toastr = require("toastr")
  3. Create app/javascript/stylesheets/application.scss file to import custom or library css files

  4. Import toastr css in app/javascript/stylesheets/application.scss

     @import 'toastr'
  5. Import app/javascript/stylesheets/application.scss file in app/javascript/packs/application.js

    import "../stylesheets/application"
  6. I wrote a helper method for flas messages. Add this method to application_helper.rb or another helper

    def toastr_flash flash.each_with_object([]) do |(type, message), flash_messages| type = 'success' if type == 'notice' type = 'error' if type == 'alert' text = "<script>toastr.#{type}('#{message}', '', { closeButton: true, progressBar: true })</script>" flash_messages << text.html_safe if message end.join("\n").html_safe end
  7. Add toastr_flash method to layouts/application.html.erb or wherever you want

    <!DOCTYPE html> <html> <head> </head> <body> <%= yield %> <%= toastr_flash %> </body> </html>

first you need to add toastr to your project

using yarn

yarn add toastr

using npm

npm -i toastr

after that you can see in your node_modules the file toastr (node_modules/toastr) inside that have the toastr.scss file and toastr.js file, well let's import it

app/assets/application.scss

@import "toastr/toastr";

app/javascripts/packs/application.js

toastr = require("toastr")

or

import toastr from 'toastr/toastr';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM