Flowdock
link_to_if(condition, name, options = {}, html_options = {}, &block) public

Creates a link tag of the given name using a URL created by the set of options if condition is true, in which case only the name is returned. To specialize the default behavior, you can pass a block that accepts the name or the full argument list for link_to_unless (see the examples in link_to_unless).

Examples

  <%= link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) %>
  # If the user isn't logged in...
  # => <a href="/sessions/new/">Login</a>

  <%=
     link_to_if(@current_user.nil?, "Login", { :controller => "sessions", :action => "new" }) do
       link_to(@current_user.login, { :controller => "accounts", :action => "show", :id => @current_user })
     end
  %>
  # If the user isn't logged in...
  # => <a href="/sessions/new/">Login</a>
  # If they are logged in...
  # => <a href="/accounts/show/3">my_username</a>
Show source
Register or log in to add new notes.
October 30, 2009
2 thanks

Outputs name even if condition is false

Please note that if the condition is false, link_to_if will still output the name given as a plain text (as documented above). If you want nothing printed at all, you’ll have to stay with the old and trusty:

link_to "Login", ... if @current_user.nil?
March 30, 2015
0 thanks

If condition is false, options hash is ignored

Here, the class will be ignored:

<%= link_to_if false, 'Home', root_path, class: 'link' %> 
#=> Home
October 30, 2009
0 thanks

Outputs name even if condition is false

Please note that if the condition is false, link_to_if will still output the name given as a plain text (as documented above). If you want nothing printed at all, you’ll have to stay with the old and trusty:

link_to "Login", ... if @current_user.nil?
March 30, 2015
0 thanks

Passing a block does not behave as expected

When the condition is true, the block is not rendered:

<%= link_to_if true, users_path, {}, {} do %>
  <i class='fa fa-star'></i>
<% end %>

renders:

<a href="/users">/users</a>

But if the condition is false, the block will render:

<%= link_to_if false, users_path, {}, {} do %>
  <i class='fa fa-star'></i>
<% end %>

renders:

<i class='fa fa-star'></i>