Conditionally Render Rails Links with `link_to_if`
ActionView::Helpers
contains some really handy helpers for conditionally rendering links. For example, the link_to_if
method will render the link if the given condition is met; otherwise it renders just the text.
<%= link_to_if(current_user.present?, "Admin Panel Tools", admin_tools_path) %>
When current_user.present?
is true
, yields the following HTML:
<a href="/admin_tools">Admin Panel Tools</a>
But when current_user.present?
is false
, yields the following:
Admin Panel Tools
https://api.rubyonrails.org/v6.0.2.1/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to_if
Note, there are also methods for link_to_unless
and link_to_unless_current