157

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?

Flip
  • 6,233
  • 7
  • 46
  • 75
Dantes
  • 2,791
  • 6
  • 26
  • 34

6 Answers6

313

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 %>  
Miles Prower
  • 105
  • 9
Baldrick
  • 23,882
  • 6
  • 74
  • 79
14

Try this:

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

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 %>
Deepak Mahakale
  • 22,834
  • 10
  • 68
  • 88
7

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

Joshua Pinter
  • 45,245
  • 23
  • 243
  • 245
ogAndrew
  • 101
  • 1
  • 9
4

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>
funfuntime
  • 261
  • 1
  • 8
2

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' })
Manuel
  • 337
  • 2
  • 6