DEV Community

matt swanson
matt swanson

Posted on • Originally published at boringrails.com on

Use Rails `link_to_unless_current` for navigation links

We’re all familiar with the classic Rails link_to helper. But did you know there is a link_to_unless_current variant?

It works just link link_to except that it doesn’t create a link if the browsers current URL is the same as the link target.

Usage

Simply replace link_to with link_to_unless_current. If you are not already on the page, a normal <a> tag will be rendered. If you are on the page already, only the text will be rendered.

<nav class="flex flex-col space-y-1">
  <%= link_to_unless_current "Dashboard", dashboard_path %>
  <%= link_to_unless_current "Team", teams_path %>
  <%= link_to_unless_current "Projects", projects_path %>
  ...
</nav>
Enter fullscreen mode Exit fullscreen mode

When you are on /dashboard, this template will output:

<nav class="flex flex-col space-y-1">
  Dashboard
  <a href="/teams">Teams</a>
  <a href="/projects">Projects</a>
  ...
</nav>
Enter fullscreen mode Exit fullscreen mode

You can also pass in a block to render (instead of the link name). This can be unless for making shared views. For instance, you could make a partial with actions for a Post.

<%= link_to_unless_current "+ Comment", new_comment_path do
  link_to "Back", posts_path
end %>
Enter fullscreen mode Exit fullscreen mode

Other Variants

As you might expect, there are other variants like link_to_if and link_to_unless if you want to specify your own conditional logic for rendering a link or not.

You might want to show a list of all Posts, but if you are logged in as an admin, the title should be a link to an edit page.

<% @posts.each do |post| %>
  <%= link_to_if @user.admin?, post.title, manage_post_path(post) %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Additional Resources

Rails API Docs: UrlHelper#link_to_unless_current

Rails API Docs: UrlHelper#link_to_if

Rails API Docs: UrlHelper#link_to_unless


Top comments (1)

Collapse
 
appmapruby profile image
AppMap Ruby

Nice little Rails feature. Optimized for developer happiness :-)