Helpers
A dynamic nav link helper that makes it easy to add active states to your nav links.
The helper includes active and inactive state options along with standard HTML options available in the link_to helper. The Ruby code is for reference only as it's included in the Rails UI gem.
name - The name of the link.
url/path - Pass the url or path to the helper.
active_class - The class to apply when the link is active based on the current path.
inactive_class - The class to apply when the link is inactive.
*html_options - pass any other html options to the link as you would a normal link_to helper.
<div class="flex items-center gap-3">
<!-- render inline -->
<%= nav_link_to "Nav Link", "#", class: "btn btn-link", active_class: "btn btn-primary", inactive_class: "btn btn-link" %>
<!-- render as block -->
<%= nav_link_to "#", class: "flex items-center gap-2 btn btn-dark", active_class: "btn btn-secondary", inactive_class: "btn btn-dark" do %>
<%= icon "home", class: "size-4 stroke-white flex-shrink-0" %>
<span>Home</span>
<% end %>
</div>
def nav_link_to(name = nil, options = {}, html_options = {}, &block)
if block
html_options = options
options = name
name = block
end
url = url_for(options)
starts_with = html_options.delete(:starts_with)
html_options[:class] = Array.wrap(html_options[:class])
active_class = html_options.delete(:active_class) || "nav-link-active"
inactive_class = html_options.delete(:inactive_class) || ""
active = if (paths = Array.wrap(starts_with)) && paths.present?
paths.any? { |path| request.path.start_with?(path) }
else
request.path == url
end
classes = active ? active_class : inactive_class
html_options[:class] << classes unless classes.empty?
html_options.except!(:class) if html_options[:class].empty?
return link_to url, html_options, &block if block
link_to name, url, html_options
end