Dantes
Dantes

Reputation: 2891

Rails: Open link in new tab (with 'link_to')

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?

Upvotes: 162

Views: 106511

Answers (6)

ogAndrew
ogAndrew

Reputation: 111

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' %>

rubocop docs

Upvotes: 8

Manuel
Manuel

Reputation: 337

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' })

Upvotes: 2

Baldrick
Baldrick

Reputation: 24350

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 %>  

Upvotes: 322

Deepak Mahakale
Deepak Mahakale

Reputation: 23711

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 %>

Upvotes: 10

funfuntime
funfuntime

Reputation: 271

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>

Upvotes: 5

Alexander Giraldo
Alexander Giraldo

Reputation: 567

Try this:

<%= link_to image_tag("facebook.png", :class => "facebook_icon", :alt => "Facebook"), "http://www.facebook.com/mypage", :target => "_blank" %>

Upvotes: 14

Related Questions