Rails: Open link in new tab (with 'link_to')
Ruby on-RailsRubyRuby on-Rails-3Ruby on-Rails Problem Overview
I have this code:
<%= link_to image_tag("facebook.png", :class => "facebook_icon", :alt => "Facebook", :target => "_blank"),
"http://www.facebook.com/mypage" %>
How can I make it open in a new tab when a user clicks the link?
Ruby on-Rails Solutions
Solution 1 - Ruby on-Rails
The target: :_blank
parameter should be a parameter of link_to
, whereas you put it in image_tag
parameters. Modify your code like this:
<%= link_to image_tag("facebook.png", class: :facebook_icon, alt: "Facebook"), "http://www.facebook.com/mypage", target: :_blank %>
Or with a block:
<%= link_to "http://www.facebook.com/mypage", target: :_blank do %>
<%= image_tag("facebook.png", class: :facebook_icon, alt: "Facebook") %>
<% end %>
Solution 2 - Ruby on-Rails
Try this:
<%= link_to image_tag("facebook.png", :class => "facebook_icon", :alt => "Facebook"), "http://www.facebook.com/mypage", :target => "_blank" %>
Solution 3 - Ruby on-Rails
You can also use target: :_blank
instead of target: '_blank'
<%= link_to image_tag("facebook.png", class: "facebook_icon", alt: "Facebook"), "http://www.facebook.com/mypage", target: :_blank %>
link_to do
<%= link_to "http://www.facebook.com/mypage", target: :_blank do %>
<%= image_tag "facebook.png", class: "facebook_icon", alt: "Facebook" %>
<% end %>
Solution 4 - Ruby on-Rails
If you're looking for how to open a link in a new tab within html (for anyone came here from Google), here:
<a href="http://www.facebook.com/mypage" target="_blank">Link name</a>
Solution 5 - Ruby on-Rails
To add on to the previous answer the format below is what is being suggested by rubocop. This can be a security risk as the loaded page will have control over the previous page and could change its location for phishing purposes.
To prevent this one needs to add on the 'rel' attribute to the code.
rel: 'noopener'
Now the link_to should be:
<%= link_to image_tag("facebook.png", class: :facebook_icon, alt: "Facebook"), "http://www.facebook.com/mypage", target: :_blank, rel: 'noopener %>
Solution 6 - Ruby on-Rails
My understanding is: you can ask the browser to open a new tab or a new site. But this depends on the user settings. I considere this question answered.
Except I fell in a trap when it is necessary to seperate the link options from the html options:
link_to(name = nil, options = nil, html_options = nil, &block)
Example:
link_to('Click me', { action: 'show', controller: 'blog', id: 1 }, { target: '_blank' })