你如何将 toastr-rails gem 添加到 Rails 6 项目中?

Dav*_*Lee 4 css ruby-on-rails toastr bootstrap-4 ruby-on-rails-6

我正在尝试将 toastr gem 添加到我的 Rails 6 项目中。我还安装了设计 gem。

我不了解 webpacker 以及如何使 toastr-rails webpacker 友好。

我已阅读所有文档。不要告诉我阅读文档。

这是我尝试过的:

yarn add toastr
Run Code Online (Sandbox Code Playgroud)

然后在我的 assets/packs/application.js 文件中,我添加了:

@import 'toastr'
Run Code Online (Sandbox Code Playgroud)

在我的 assets/stylesheets/application.scss 文件中,我添加了:

*= require_toastr
Run Code Online (Sandbox Code Playgroud)

最后我的 layouts/application.html.erb 有这个代码:

<!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>
Run Code Online (Sandbox Code Playgroud)

我没有收到 Toast 通知。我没有收到任何通知。但是这段代码适用于我的 Rails 4 项目。

dem*_*mir 12

如果您想使用 toastr-rails gem 添加 toastr,请使用资产管道而不是 webpack。

以下是toastr使用webpack.

  1. 用纱线添加 toastr js

    yarn add toastr
    
    Run Code Online (Sandbox Code Playgroud)
  2. app/javascript/packs/application.js 中需要 toastr 。我将它添加到全局以避免错误

    global.toastr = require("toastr")
    
    Run Code Online (Sandbox Code Playgroud)
  3. 创建app/javascript/stylesheets/application.scss文件以导入自定义或库 css 文件

  4. app/javascript/stylesheets/application.scss 中导入 toastr css

    @import 'toastr'
    
    Run Code Online (Sandbox Code Playgroud)
  5. app/javascript/packs/application.js 中导入app/javascript/stylesheets/application.scss文件

    import "../stylesheets/application"
    
    Run Code Online (Sandbox Code Playgroud)
  6. 我为 flas 消息编写了一个辅助方法。将此方法添加到application_helper.rb或其他帮助程序

    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
    
    Run Code Online (Sandbox Code Playgroud)
  7. toastr_flash方法添加到layouts/application.html.erb或任何你想要的地方

    <!DOCTYPE html>
    <html>
      <head>
      </head>
      <body>
        <%= yield %>
        <%= toastr_flash %>
      </body>
    </html>
    
    Run Code Online (Sandbox Code Playgroud)


小智 5

首先,您需要将 toastr 添加到您的项目中

使用纱线

yarn add toastr
Run Code Online (Sandbox Code Playgroud)

使用 npm

npm -i toastr
Run Code Online (Sandbox Code Playgroud)

之后你可以在你的 node_modules 中看到文件 toastr (node_modules/toastr) 里面有 toastr.scss 文件和 toastr.js 文件,让我们导入它

应用程序/资产/application.scss

@import "toastr/toastr";
Run Code Online (Sandbox Code Playgroud)

应用程序/javascripts/packs/application.js

toastr = require("toastr")
Run Code Online (Sandbox Code Playgroud)

或者

import toastr from 'toastr/toastr';
Run Code Online (Sandbox Code Playgroud)