问题 来自Rails 4中控制器的html_safe的Flash消息(安全版)


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

    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称为unescape字符串。但是,从Rails 4.1开始,现在处理的方式不同了。 (看到 这里 和 这里

已经提供了对此的解决方案 这个问题。但是,它只能通过移动来实现 html_safe 调用视图,具有取消所有flash消息的效果。

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


12150
2017-10-23 22:59


起源



答案:


这是解决此问题的一种可能方法。添加一个前过滤器到您的 ApplicationController 这将使 flash[:notice] html安全只有 flash[:html_safe] 已设定。然后你可以控制什么时候和什么时候不要让通知html完全从控制器安全。

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

然后您的示例可以修改为:

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

16
2017-10-24 12:00



奇迹般有效!谢谢。 =) - 0112
从Rails 4.2开始,这在控制器试用闪存中不起作用[:notice] =“soem string <br> more text”.html_safe - user1136228
@ user1136228我刚刚尝试使用Rails 4.2.1和4.2.5,它确实有效。请检查您的代码。 - Wizard of Ogz
#html_safe 在Rails 4.2.1中不适用于此用例。我已经做了 flash[:warning] = "<a href='#'>Click Me</a>'".html_safe 并在页面上将html打印为字符串。 - sixty4bit
@ sixty4bit在一个请求结束时,闪存中的数据被序列化为数据存储区(cookie,数据库,redis,memcached等)。然后在下一个请求开始时反序列化。在此序列化和反序列化过程中,不会保留html_safe信息(尽管可以实现)。 - Wizard of Ogz


答案:


这是解决此问题的一种可能方法。添加一个前过滤器到您的 ApplicationController 这将使 flash[:notice] html安全只有 flash[:html_safe] 已设定。然后你可以控制什么时候和什么时候不要让通知html完全从控制器安全。

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

然后您的示例可以修改为:

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

16
2017-10-24 12:00



奇迹般有效!谢谢。 =) - 0112
从Rails 4.2开始,这在控制器试用闪存中不起作用[:notice] =“soem string <br> more text”.html_safe - user1136228
@ user1136228我刚刚尝试使用Rails 4.2.1和4.2.5,它确实有效。请检查您的代码。 - Wizard of Ogz
#html_safe 在Rails 4.2.1中不适用于此用例。我已经做了 flash[:warning] = "<a href='#'>Click Me</a>'".html_safe 并在页面上将html打印为字符串。 - sixty4bit
@ sixty4bit在一个请求结束时,闪存中的数据被序列化为数据存储区(cookie,数据库,redis,memcached等)。然后在下一个请求开始时反序列化。在此序列化和反序列化过程中,不会保留html_safe信息(尽管可以实现)。 - Wizard of Ogz