2015-11-17 19 views
2

我想包括在動態Twitter的分享鏈接與錨文章鏈接的Rails link_to方法:逃生#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之前添加一個#字符,因爲它在我看來是一個錨鏈接。我似乎無法讓#正常逃脫。這甚至有可能嗎?

+0

可能的重複[如何轉義#{從字符串插值](http://stackoverflow.com/questions/1310701/how-do-i-escape-from-string-interpolation) –

+0

@cantido我看到答案和它有點不同。我基本上想在'#{article.title}之前添加一個額外的'#',但似乎並不需要。思考? – gitastic

+0

我明白你的意思了。我試過'「\ ## {article.title}」'這在我的IRB中有效,它對你有用嗎? –

回答

0

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

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

看起來像它呈現爲一個包括hashtag(#thattookwaytoolongtofigureout #ihopethishelpssomeone)

+0

我可以確認Chrome在URL字符串中使用常規哈希標籤替換該字符。 –

0

總的來說這是一個壞主意,用繩子concatenation- 特別打造的網址當你需要做一些像在另一個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 %> 

正如也許你已經猜到了,它可能是最好把所有這一切在一個幫手:

​​
<%= link_to tweet_url(article.title) do %> 
    <span class="fa fa-twitter-square fa-2x"></span> 
<% end %> 

(你可以,當然,將上述內容減少到單個雙行幫手,但代價是可讀性和可測試性,但這將是一個錯誤。)