Mur Quirk
Mur Quirk

Reputation: 171

Rails: conditional home link

I'm currently using

<li><%= link_to_unless_current("Home", root_path) %></li> 

to show a Home link on the nav bar when they are not at the root path. It works fine except it leaves behind the text "Home" (not the link, just text) when they are at the root path.

I'm sure there's a better way to do this, any tips?

Upvotes: 2

Views: 1761

Answers (4)

azaytc
azaytc

Reputation: 63

I suppose it's better to not use link_to_unless, or link_to_if, because it confuses user. Better to change its style or background and leave link to easily reload page clicking on the link.

Upvotes: 0

Mischa
Mischa

Reputation: 43318

You can do this to omit "Home":

<%= link_to_unless_current("Home", root_path) { "" } %>

The API shows that if you want to do something else than just returning the name, you can pass in a block and do what you want, which in this case is returning an empty string.

Upvotes: 1

Benjamin Tan Wei Hao
Benjamin Tan Wei Hao

Reputation: 9701

link_to("Home", root_path) unless current_page?(root_url)

Upvotes: 6

Taryn East
Taryn East

Reputation: 27757

link_to_unless_current works by doing this:

  1. if the condition is true, it will put the link in place
  2. if the condition is not true, it will just put the text (without a link).

This function is usually used in a menu where you still want the "current" option to show up, even if you're on that page - generally you'll often want to highlight it somehow.

if you want the link to not show up at all, just do a "normal" link-to and use unless on the whole link_to method-call. eg Benjamin Tan's example:

link_to("Home", root_path) unless current_page?(root_path)

Upvotes: 0

Related Questions