Skip to content

Instantly share code, notes, and snippets.

@simptive
Last active December 10, 2023 18:07
Show Gist options
  • Save simptive/3d732d3801e048eca72d8d9fc9b5c9b8 to your computer and use it in GitHub Desktop.
Save simptive/3d732d3801e048eca72d8d9fc9b5c9b8 to your computer and use it in GitHub Desktop.
Dynamic Breadcrumbs / Navigation history in Rails
<%# Relevant methods/vars: heading, navigation_add, render_navigation %>
<!DOCTYPE html>
<html>
<%# header content %>
<body>
<section class="content-header">
<% heading = yield(:heading).truncate(30) %>
<h1><%= heading %></h1>
<% navigation_add (heading), request.fullpath %>
<%= render_navigation %>
</section>
<section class="content"><%= yield %></section>
</body>
</html>
<%
# This should be in separate helpers/navigation_helper.rb
module NavigationHelper
def navigation_add(title, url)
nav_list = session['navigation'].present? ? session['navigation'] : []
nav_list << { 'title' => title, 'url' => url }
# If first is pointing root, remove it
nav_list.shift if nav_list[0]['url'] == '/'
# If last one is same as its predecessor (except query string), remove it
nav_list.pop if nav_list.length > 1 && (nav_list[-1]['url'].split('?')[0] == nav_list[-2]['url'].split('?')[0])
# Take last 3 items only (-1 is last, not -0)
nav_list = nav_list[-3..-1] if nav_list.length > 3
session['navigation'] = nav_list
end
def render_navigation
render partial: 'shared/navigation', locals: { nav_list: session['navigation'] }
end
end
%>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment