【问题标题】:How can I tell Rails/HAML to not escape a URL?如何告诉 Rails/HAML 不要转义 URL?
【发布时间】:2011-12-14 18:46:59
【问题描述】:

我有这个代码:

= link_to "unsubscribe instantly", "*|UNSUB|*".html_safe

生成这个 HTML:

<a href="*%7CUNSUB%7C*">unsubscribe instantly</a>

该 |字符被转义。这行不通,因为我将此 HTML 发送到应该用取消订阅 url 替换 *|UNSUB|* 的服务。

相反,我希望 Rails/HAML 生成这个:

<a href="*|UNSUB|*">unsubscribe instantly</a>

我去了http://haml-lang.com/try.html 并输入了%a{:href =&gt; "*|UNSUB|*"} unsubscribe 并且输出是我所期望的。所以我猜这是 Rails 的问题。


更新:我在一个新的 Rails 3.1 应用程序上尝试了这个,管道没有被转义——这正是我想要的。我的主要 Rails 应用程序发生了一些奇怪的事情,导致 URL 被转义 - 现在进一步调查。


更新: 我想到了。我有一些 Rack 中间件正在运行类似的东西:
content = Nokogiri(response)
# ... processing
return content.to_html

这是对 URL 中的内容进行编码。我在这里问了一个相关的问题:Preventing Nokogiri from escaping characters in URLs

【问题讨论】:

  • 你试过!= link_to("unsubscribe instantly", "*|UNSUB|*".html_safe).html_safe 吗? post

标签: ruby-on-rails escaping haml html-escape-characters


【解决方案1】:

这些真的逃脱了吗?我刚刚用 rails 3.0.3(编辑:和 rails 3.1.1)做了一个测试,这些:

= link_to 'unsubscribe instantly', '*|UNSUB|*'   
%a{:href => '*|UNSUB|*'} unsubscribe instantly
:plain
  <a href="*|UNSUB|*">unsubscribe instantly</a>

然后我在页面上使用 curl,管道似乎就在那里:

curl http://localhost:3000/about | grep UNSUB
<a href="*|UNSUB|*">unsubscribe instantly</a>
<a href='*|UNSUB|*'>unsubscribe instantly</a>
<a href="*|UNSUB|*">unsubscribe instantly</a>

【讨论】:

  • 很奇怪。我使用 curl 进行测试,管道仍然被逃脱。我将尝试一个新的 Rails 应用程序。
  • 在一个新的 Rails 应用程序中,URL 没有被转义(这是我想要的)。在我用来测试的其他 Rails 应用程序中,我必须有一些不同的配置或 gem。
【解决方案2】:

我想通了。我有一些 Rack 中间件正在运行类似的东西:

content = Nokogiri(response)
# ... processing
return content.to_html

这是对 URL 中的内容进行编码。

【讨论】:

    【解决方案3】:

    您是否尝试过跳过link_to 而只是直接创建链接标签

    a{:href=>"*|UNSUB|*"} unsubscribe instantly
    

    【讨论】:

    • HAML 会将其转换为 立即取消订阅,这不是我想要的。
    • a(href='*|UNSUB|*') unsubscribe instantly 怎么样?
    【解决方案4】:

    这对你有用吗:

    =! link_to "unsubscribe instantly", "*|UNSUB|*"
    

    (意识到它或多或少是等效的,但可能会有所不同)

    【讨论】:

    • 对不起我的错!我的意思是!= link_to "unsubscribe instantly", "*|UNSUB|*"
    • 还是没有运气。输出 取消订阅
    【解决方案5】:

    我没有地方对此进行测试,但这会起作用吗?

    - html = "<a href="*|UNSUB|*">unsubscribe instantly</a>"
    = raw html
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-26
    • 2013-12-28
    • 2012-12-11
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    相关资源
    最近更新 更多