joe
joe

Reputation: 1026

Rails: How to add link_to with target blank

I am new to rails 3, I would like to add (:target => "_blank") to link_to helper below

link_to "GOOGLE", 'http://www.google.com', class: "btn btn-large btn-primary"

But I would like to use the application_helper to define link_to method.

  1. How do I define the link_to methd in application_helper?
  2. How do I pass the class: "btn btn-large btn-primary" in the link_to method?

Thank you for your assistance...

Upvotes: 86

Views: 69221

Answers (3)

Aidi Stan
Aidi Stan

Reputation: 151

Up to now for Rails 7, I suggest a more elegant way according to Rails's implementation of link_to:

def link_to(name = nil, options = nil, html_options = nil, &block)
  html_options, options, name = options, name, block if block_given? 
  link_to(name, options, (html_options || {}).merge(target: '_blank'))
end

Upvotes: 0

Anthony Alberto
Anthony Alberto

Reputation: 10405

Why would you want to override link_to? It's already defined in Rails, just use it like this :

link_to "GOOGLE", "http://www.google.com", target: "_blank", class: "btn btn-large btn-primary"

Edit: OK, understood. I'd advise against overriding such a common method so create another one :

def link_to_blank(body, url_options = {}, html_options = {})
  link_to(body, url_options, html_options.merge(target: "_blank"))
end

It should do the trick

Upvotes: 162

Benjamin Sullivan
Benjamin Sullivan

Reputation: 1476

Adding to Anthony's answer, this more closely resembles Rails' link_to implementation, including support for blocks and passing no parameters:

def link_to_blank(name = nil, options = nil, html_options = nil, &block)
  target_blank = {target: "_blank"}
  if block_given?
    options ||= {}
    options = options.merge(target_blank)
  else
    html_options ||= {}
    html_options = html_options.merge(target_blank)
  end
  link_to(name, options, html_options, &block)
end

Upvotes: 5

Related Questions