开发者

Custom links in Rails

Rails has a few built in helper methods for dealing with links (url_for, link_to, auto_link), but none do exactly what I need:

I want the user to be able to specify a URL, and for me to be able to alter the text it appears as. auto_link almost does what I want, except you can't change the link text, and it doesn't recognize links that are typed in like: stackoverflow.com. You have to enter www.stackoverflow.com

I want the user to be able to enter something like "stackoverflow.com", and for me to be able to generate html like this:

&开发者_运维知识库lt;a href="http://www.stackoverflow.com">Username</a>

Is there a plugin out there that adds additional link helper methods?


You can pass a block to auto_link, and the result of that will be the link text. For example:

<% str = "something like http://stackoverflow.com would be the input" %>
<%= auto_link(str) do |url|
      "Username"
    end
%>

generates this HTML:

something like <a href="http://stackoverflow.com">Username</a> would be the input

And if you wanted the link text to be different depending on what the URL was, you could do something like:

<% str = "something like http://stackoverflow.com, and another http://stackexchange.com url" %>
<%= auto_link(str) do |url| 
  if url.match(/overflow/) 
    "Username"
  else
    "Something"
  end
end %>

which generates:

something like <a href="http://stackoverflow.com">Username</a>, and another <a href="http://stackexchange.com">Something</a> url

This plus the tips in the comments about adjusting the URL regex seem like they would do what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜