【问题标题】:Rails 4 - Toaster notifications rather than flash notificationsRails 4 - Toaster 通知而不是 Flash 通知
【发布时间】:2013-09-07 09:25:25
【问题描述】:

我正在使用这个库 (https://github.com/CodeSeven/toastr),我正在尝试将我的 Flash 通知推送到 Toastr 为我提供的 javascript 函数。如何为每个错误或通知调用此函数?

这是用于制作烤面包机通知的方法之一:

toastr.warning('This is a warning!')

我尝试在 ApplicationController 中创建一个方法,以查看是否可以针对 CanCan 的默认错误调用该方法。我有各种版本的方法,但都不起作用。

def toast(type, text)
    #if Logic here for various errors/notifications
    respond_to do |format|
        format.js { render action: "toastr.warning(#{text})", layout: false}
    end
end

def toast(type, text)
    #if Logic here for various errors/notifications
    "toastr.warning(#{text})"
end

然后我尝试在 CanCan 块中使用此方法:

rescue_from CanCan::AccessDenied do |exception|
    toast :error, exception.message
    redirect_to root_url
end

我认为这是可能的,但我只是不确定如何实现它。没有多少人尝试这样做,这可能是有原因的。我愿意接受有关如何做我想做的事情的任何建议。

这是一个实现 Toast 通知的测试应用程序: http://codeseven.github.io/toastr/demo.html

【问题讨论】:

    标签: javascript ruby-on-rails notifications ruby-on-rails-4 toastr


    【解决方案1】:

    我建议为这类事情创建一个新的 flash 类型,然后在布局中将其呈现为 JS。

    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 %>
    

    因此,通过这种方式,您可以从 flash 对象中获得您习惯的所有标准行为,并且您可以轻松理解直接通过 erb 在视图中编写的 javascript。当然,您可能需要向 ApplicationController#toast 方法添加选项哈希,以便您有时可以执行 flash.now[:toastr]。等等......但这应该让你开始。

    【讨论】:

    • 稍加调整,例如在message.inspect 上添加Raw。我让它工作了。感谢您的帮助!
    猜你喜欢
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多