【问题标题】:How can I output raw unescaped html from this Rails route/helpers?如何从此 Rails 路线/帮助程序输出原始未转义的 html?
【发布时间】:2011-09-27 20:27:11
【问题描述】:

我正在尝试使用以下代码在我的页面上生成链接

%h2= link_to '{{ label }}', product_path('{{ id }}'.html_safe)

这实际上是一个更大的 HTML 块的一部分,它将用作 javascript 模板,稍后我将使用 Underscore.js 进行解析以填充 {{ id }}{{ label }} 占位符。所以我希望 rails 能够向我的 HTML 输出一些东西,比如

/products/{{ id }}

但是,它不断逃避空格和括号,并给我

<a href="/products/%7B%7B%20id%20%7D%7D">{{ label }}</a>

所以 url_helper 正在转义我的字符串,即使我不希望它这样做。我怎么能强迫它不这样做?

我试过了

%h2= link_to '{{ label }}', product_path('{{ id }}'.html_safe)
%h2= link_to '{{ label }}', product_path(raw '{{ id }}')
%h2= link_to '{{ label }}', raw(product_path('{{ id }}'))

%h2=raw( link_to '{{ label }}', product_path('{{ id }}'.html_safe))

但它们都不起作用

编辑:

另一种玩这个的方法是从rails控制台,

include ActionController::UrlWriter

ruby-1.9.2-p0 :010 > product_path '{{ id }}'.html_safe
 => "/products/%7B%7B%20id%20%7D%7D" 

任何帮助表示赞赏...谢谢

谢谢

【问题讨论】:

  • 现在是 2019 年,我们仍然面临类似的问题!

标签: html ruby-on-rails escaping routes helpers


【解决方案1】:

CGI::unescape(product_path('{{ id }}') 呢? (附带require 'cgi'。)

我相信这只是 Ruby 1.9.2,但它似乎是您正在使用的版本。

【讨论】:

  • 作为记录,您的解决方案似乎是永恒的,因为它仍然适用于 Ruby 2.6.3 和 Rails v5.2.3!谢谢!
  • 在我最近获得投票时添加对我这个 10 年前的答案的评论:如果你这样做,请确保 unescaped 数据不是用户控制的,因为它可以打开XSS 的门。
猜你喜欢
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 2015-04-16
  • 2023-03-26
  • 2015-07-15
  • 1970-01-01
  • 2015-09-08
  • 2013-03-21
相关资源
最近更新 更多