Foliosus Web Design LLC: Your website done right

Blogfolio

An "else" condition for link_to_unless_current

Apr 18 ’07

Every time I get frustrated with an aspect of Rails, it turns out that it's just my idiocy and not actually something to do with Rails.

Most recently, I wanted to code this algorithm:

If on the current page
  show <a href="blah1">link 1</a>
else
  show <a href="blah2>link 2

Rails has, of course, the nifty link_to_unless_current, but all that does is show the text of the link:

If on the current page
  show link
else
  show <a href="blah">link</a>

That's not quite what I'm looking for. But when I was looking up link_to_unless_current in the docs, I realized that there IS an else condition on link_to_unless_current. The function takes a block as its last parameter, and that's what gives you the "else."

This code, in a view:

<%= link_to_unless_current('Link text', my_url) { 'Alternate text' } %>

produces this algorithmic result:

If on the current page
  show Alternate text
else
  show <a href="my_url">Link text</a>

Mission accomplished.

    Start the conversation

    * indicates a required field

    New comment

    Will never be disclosed or used inappropriately

    Enter the word how to confirm that you are a human being

    About the author

    Brent Miller is the owner and principal web designer of Foliosus Web Design LLC in Portland, Oregon. He enjoys food, plants, and the color green. If you are interested in hiring him for web work, please contact him.

    Categories

    Plant of the day

    Unknown sp.

    Unknown sp.

    Fresh photos