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
.
Add toastr js with yarn
yarn add toastr
Require toastr in app/javascript/packs/application.js. I added it to the global to avoid errors
global.toastr = require("toastr")
Create app/javascript/stylesheets/application.scss file to import custom or library css files
Import toastr css in app/javascript/stylesheets/application.scss
@import 'toastr'
Import app/javascript/stylesheets/application.scss file in app/javascript/packs/application.js
import "../stylesheets/application"
I wrote a helper method for flash 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
Add toastr_flash
method to layouts/application.html.erb or wherever you want
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<%= yield %>
<%= toastr_flash %>
</body>
</html>
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