简体   繁体   中英

How do I convert this a href into a Rails friendly link_to

I would like to convert this:

<a class="btn btn-google-plus" href="https://plus.google.com/share?url=SHAREMESSAGE" title="Share on Google+" target="_blank">
     <i class="fa fa-google-plus"></i>
</a>

Into a Rails friendly link_to that not uses post.title in the URL and also includes a link to the current post.

In other words, I started by doing this in HTML like this:

<a class="btn btn-google-plus" href='https://plus.google.com/share?url=<%= "#{post.title} - Read more at #{post}" %>' title="Share on Google+" target="_blank">
    <i class="fa fa-google-plus"></i>
</a>

The issue with this is that this generates a URL like this (the Twitter equivalent, but the principle is the same):

http://twitter.com/home?status=PNPYO%20saddened%20at%20passing%20of%20Roger%20Clarke%20-%20Read%20more%20at%20#<Post:0x00000101660e98>

Where it returns a Post object. The issue I ran into quickly, was that I wasn't quite sure how to generate a link_to within a link_to . Is that even possible?

This is how I want the final status on Twitter to look:

PNPYO saddened at passing of Roger Clarke - Read More at http://example.com/pnpyo-saddened-at-passing-of-roger-clarke

How do I achieve this in the most Rails-friendly way possible? I am not averse to just using regular a href tags, if it can't be done with a link_to helper. But either way, I still need to be able to generate a link_to within the status message.

You can achieve as follow :

<%= link_to "https://plus.google.com/share?url=#{post.title} - Read more at #{post}", :class => "btn btn-google-plus" :title => "Share on Google+" :target => "_blank" do %>
  <i class="fa fa-google-plus"></i>
<% end %>

You don't want to call a link_to within a link_to , but you want to call an url_helper directly.

link_to in rails is a helper method which generates the necessary html code for links. Whether you want to use this convenience function or not, what you are searching for is a direct method to generate an url that you can concatenate into a string.

Simply use the following as the href for your anchor:

http://twitter.com/home?status=<%=u "#{post.title} - Read more at #{post_url(post)}" %>

(<%=u %> performs the url encoding of the string)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM