如何自定义通知的外观 - toastr-rails

How can I customize the look of the notifications - toastr-rails

我正在尝试自定义 toast 的位置。

我试过了,但没用:

applications.js

//= require jquery
    //= require toastr
    //= require jquery_ujs
    //= require turbolinks
    //= require_tree .

    $(document).ready(function() {


     toastr.options = {
                      "closeButton": false,
                      "debug": false,
                      "positionClass": "toast-bottom-right",
                      "onclick": null,
                      "showDuration": "300",
                      "hideDuration": "1000",
                      "timeOut": "5000",
                      "extendedTimeOut": "1000",
                      "showEasing": "swing",
                      "hideEasing": "linear",
                      "showMethod": "fadeIn",
                      "hideMethod": "fadeOut"
                  }

    });

我正在使用 rails 5,有人知道为什么它不起作用吗? 提前谢谢。

你用toastr-rails吗?

我试过用它,但我做不到,所以现在我直接使用 toastr:https://github.com/CodeSeven/toastr

只需添加 application.js,创建一个类似这样的部分:

<% unless flash.empty? %>
<script type="text/javascript">
    <% flash.each do |f| %>
        <% type = f[0].to_s.gsub('alert', 'error').gsub('notice', 'info') %>
        toastr['<%= type %>']('<%= f[1] %>', '', {"closeButton": false, "debug": false, "positionClass": "toast-bottom-full-width", "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" });
    <% end %>
</script>

请注意,选项内嵌在代码中。

我知道这个 post 有点旧,但以防将来其他人偶然发现它,下面是我如何使用 gem 'toastr-rails' 在我的 [=22] 中使用 toastr =] 文件.

//= require jquery
//= require jquery_ujs
//= require toastr
//= require_tree .

/*global toastr*/
toastr.options = {
  "closeButton": false,
  "debug": false,
  "positionClass": "toast-bottom-right",
  "onclick": null,
  "showDuration": "300",
  "hideDuration": "1000",
  "timeOut": "5000",
  "extendedTimeOut": "1000",
  "showEasing": "swing",
  "hideEasing": "linear",
  "showMethod": "fadeIn",
  "hideMethod": "fadeOut"
}

对我来说,我需要添加 /*global toastr*/ 行,因为我收到控制台错误,告诉我 'toastr' 不是变量。然后你可以使用你想要的任何选项。不要忘记将 *= require toastr 也添加到您的 application.css 文件中。

再次希望这对以后的人有所帮助。

toastr-rails 现在已经过时了,我强烈建议添加独立的 toastr。如果你使用的是Rails 5+,你可以用yarn添加toastr:

yarn add toastr

当然,您仍然可以下载 toastr,也可以复制并粘贴到资产中 - 如果您没有 yarn。

然后添加助手:

module FooHelper
  def toastr_flash_class(type)
    case type
    when "alert"
      "toastr.error"
    when "notice"
      "toastr.success"
    else
      "toastr.info"
    end
  end
end

创建部分,例如 _toaster.html.erb

<%= content_tag(:script) do %>
  <% flash.each do |type, message| %>
    <%= toastr_flash_class("#{type}") %>('<%= message %>')
  <% end %>
<% end %>

从您的布局或视图中调用您的部分:

<%= render 'layouts/shared/toastr' %>