来自 Rails 4 控制器的带有 html_safe 的 Flash 消息(安全版本) [英] Flash message with html_safe from the controller in Rails 4 (safe version)

查看:29
本文介绍了来自 Rails 4 控制器的带有 html_safe 的 Flash 消息(安全版本)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的控制器中,我有以下代码:

In my controller I have the following code:

    format.html { redirect_to new_customer_url,
                notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.
    ].html_safe

我希望能够在 flash 消息中包含一个链接,因此(如您所见)我调用 html_safe 来取消对字符串的转义.然而,从 Rails 4.1 开始,这似乎是不同的处理方式.(请参阅此处这里)

I would like to be able to include a link in a flash message, so (as you can see) I call html_safe to unescape the string. However, it seems that as of Rails 4.1 this is now handled differently. (See here and here)

这个问题.但是,它只能通过将 html_safe 调用移动到视图来实现,从而具有对所有 Flash 消息进行转义的效果.

A solution to this has been provided in this question. However, it only does so by moving the html_safe call to the view, having the effect of unescaping all flash messages.

我宁愿比这更偏执一点,有没有办法将链接包含在控制器的 flash 消息中?

I would prefer to be a bit more paranoid than that, is there any way to include the link in the flash message from the controller?

推荐答案

这是解决此问题的一种可能方法.向您的 ApplicationController 添加一个 before 过滤器,只有在设置了 flash[:html_safe] 时,它才会使 flash[:notice] html 安全.然后你可以控制什么时候什么时候不让通知 html 完全从控制器安全.

Here is one possible way to solve this problem. Add a before filter to your ApplicationController which will make flash[:notice] html safe only if flash[:html_safe] is set. Then you can control when and when not to make notices html safe completely from the controller.

before_filter -> { flash.now[:notice] = flash[:notice].html_safe if flash[:html_safe] && flash[:notice] }

那么您的示例可以修改为:

Then your example could be modified to this:

format.html do
  redirect_to(
    new_customer_url,
    notice: %Q[ A customer already exists with with this shopping id. Edit this customer #{view_context.link_to("here", edit_customer_url(@duplicate))}.],
    flash: { html_safe: true }
  )
end

这篇关于来自 Rails 4 控制器的带有 html_safe 的 Flash 消息(安全版本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆