Skip to content

Instantly share code, notes, and snippets.

@heratyian
Last active October 24, 2024 15:07
Show Gist options
  • Save heratyian/4604ae64c3c4a0e1774d5d4336cc10e3 to your computer and use it in GitHub Desktop.
Save heratyian/4604ae64c3c4a0e1774d5d4336cc10e3 to your computer and use it in GitHub Desktop.
Breadcrumbs 🍞

Ruby on Rails implementation of Bootstrap Breadcrumb

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  ...
  def show
    @breadcrumbs = [
      {content: "Posts", href: posts_path},
      {content: @post.to_s},
    ]
  end
  ...
end
<!-- app/views/shared/_breadcrumbs.html.erb -->
<% if @breadcrumbs.present? %>
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
      <% @breadcrumbs.each do |breadcrumb| %>
        <% if breadcrumb == @breadcrumbs.last %>
          <li class="breadcrumb-item active" aria-current="page">
            <%= breadcrumb.fetch(:content) %>
          </li>
        <% else %>
          <li class="breadcrumb-item">
            <%= link_to breadcrumb.fetch(:content), breadcrumb[:href] %>
          </li>
        <% end %>
      <% end %>
    </ol>
  </nav>
<% end %>
<!-- app/views/layouts/application.html.erb -->
<body>
  <%= render "shared/breadcrumbs" %>
  <%= yield %>
</body>
# app/models/post.rb

# id
# title
# body
# author_id
class Post < ApplicationRecord
  def to_s
    "#{title} #{author.name}"
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment