【问题标题】:Escape # in Rails link_to, Twitter Share linkEscape # in Rails link_to, Twitter Share link
【发布时间】:2016-02-18 08:24:24
【问题描述】:

我正在尝试使用 Rails link_to 方法在 Twitter 共享链接中动态包含锚定文章链接:

<%= link_to "http://twitter.com/home?status=Check Out #{article.title} link.com/#{article.title.parameterize}" do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

Twitter 链接将内容输出分享到:

查看文章标题 link.com/ARTICLE-TITLE。

问题是我想在 ARTICLE-TITLE 之前添加一个# 字符,因为它在我看来是一个锚链接。我似乎无法让# 正确逃脱。这甚至可能吗?

【问题讨论】:

  • @cantido 我看到了这个答案,但有点不同。我基本上想在'#{article.title}之前添加一个额外的'#',但似乎不需要。想法?
  • 我明白你的意思。我试过"\##{article.title}",它在我的 IRB 中有效,对你有用吗?
  • @cantido 我已经尝试过了,但由于某种原因,它不会在 Twitter 共享链接中呈现。 twitter 中的输出是:link.com/
  • @cantido 它甚至不会像你建议的那样在输入 \# 时呈现 #{article.title}

标签: ruby-on-rails ruby-on-rails-4 twitter escaping link-to


【解决方案1】:

%23 = #(在 Twitter 分享链接中)。

例如。 link.com/%23#{article.title.parameterize}

看起来它已呈现为主题标签 (#thattookwaytoolongtofigureout #ihopethishelpssomeone)

【讨论】:

  • 我可以确认 Chrome 会在 URL 字符串中将该字符替换为常规主题标签。
【解决方案2】:

一般来说,使用字符串连接构建 URL 是个坏主意——尤其是,当您需要执行诸如将 URL 放入另一个 URL 的查询参数之类的操作时。

要创建正确编码的查询参数,请使用 Rails 方便的Hash#to_query 方法。

让我们从内到外。

# Build the article URL
article_base_url = 'http://example.com/path'
article_url_hash = article.title.parameterize # => "my-article"
article_url = "#{article_base_url}##{article_url_hash}"
# => "http://example.com/path#my-article"

# Next, build the query string for the tweet URL
tweet_url_query = {
  status: "Check out #{article.title} #{article_url}"
}.to_query
# => "status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"

# Finally, build the tweet URL:
base_tweet_url = 'https://twitter.com/home'
tweet_url = "#{base_tweet_url}?#{tweet_url_query}"
# => "https://twitter.com/home?status=Check%20out%20My%20Article%20http%3A%2F%2Fexample.com%2Fpath%23my-article"
<%= link_to tweet_url do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

也许你已经猜到了,最好把这一切都放在一个 helper 中:

ARTICLE_BASE_URL = 'http://example.com/'
TWEET_BASE_URL = 'http://twitter.com/home'

def tweet_url(title) 
  query = { status: tweet_text(title) }.to_query
  "#{TWEET_BASE_URL}?#{query}"
end

def tweet_text(title)
  "Check out #{title} #{article_url(title)}"
end

def article_url(title)
  "#{ARTICLE_BASE_URL}##{title.parameterize}"
end
<%= link_to tweet_url(article.title) do %>
  <span class="fa fa-twitter-square fa-2x"></span>
<% end %>

(当然,您可以以牺牲可读性和可测试性为代价将上面的内容简化为一个两行的辅助函数,但这将是一个错误。)

【讨论】:

    猜你喜欢
    • 2013-03-06
    • 2014-02-23
    • 2014-11-03
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多