erb javascript 89 lines · 3 tabs

Keep navbar state across Turbo navigations with data-turbo-permanent

Shared by codesnips Jan 2026
3 tabs
<nav id="main-navbar"
     data-turbo-permanent
     data-controller="navbar"
     data-navbar-menu-open-value="false"
     class="navbar">
  <div class="navbar-inner">
    <%= link_to "Acme", root_path, class: "navbar-brand" %>

    <button type="button"
            class="navbar-toggle"
            data-action="click->navbar#toggle"
            aria-controls="navbar-menu"
            aria-expanded="false">
      <span class="sr-only">Toggle menu</span>
      &#9776;
    </button>

    <div id="navbar-menu"
         class="navbar-menu"
         data-navbar-target="menu">
      <%= link_to "Dashboard", dashboard_path, class: "navbar-link", data: { navbar_target: "link" } %>
      <%= link_to "Projects", projects_path, class: "navbar-link", data: { navbar_target: "link" } %>
      <%= link_to "Settings", settings_path, class: "navbar-link", data: { navbar_target: "link" } %>
    </div>
  </div>
</nav>
3 files · erb, javascript Explain with highlit

When Rails apps use Turbo Drive, clicking a link swaps only the <body> contents while keeping the page alive, but by default the entire body is replaced — so a navbar dropdown that was open, or a search input mid-typing, gets wiped on every navigation. The fix is data-turbo-permanent, which tells Turbo to preserve a specific element across page loads by matching its id. This snippet shows the full loop: the persistent markup, the Stimulus controller that owns its runtime state, and the layout that must keep the same element id on every page for the persistence to work.

In _navbar.html.erb, the outer <nav> carries data-turbo-permanent and a stable id="main-navbar". Because Turbo sees the same id in the incoming document, it lifts the existing DOM node out and reinserts it rather than re-rendering it. The mobile menu toggle and the connected dropdown controller therefore survive the swap untouched. Note the data-turbo-permanent element must have an id and must appear identically in the next page, otherwise Turbo discards it.

The navbar_controller.js Stimulus controller holds the open/closed state in a plain boolean and a menuOpen value, not in a re-rendered server partial. Because the element is permanent, connect() runs once and is not called again on later navigations, so the controller keeps its this.open state naturally. The toggle() action flips visibility, and closeOnNavigate listens for turbo:before-render to optionally collapse menus so the user does not land on a new page with a stale open dropdown.

A subtle trade-off: permanent elements do not get their event listeners rebound, and Stimulus intentionally skips disconnect/connect for them. That is the desired behavior for state, but it means any per-page data injected server-side into that node will go stale — so the navbar should read dynamic bits (like the current path for active-link styling) from Turbo events rather than from the frozen markup.

The application.html.erb layout renders the same _navbar partial inside <body> on every response. Keeping the partial identical across layouts is what makes the id match hold. This pattern is ideal for navbars, audio players, flash containers, and chat widgets — anything whose live state should outlive a navigation without a full SPA framework.


Related snips

ruby
class CommentsController < ApplicationController
  before_action :set_post

  def create
    @comment = @post.comments.build(comment_params)

System test: asserting Turbo Stream responses

rails hotwire turbo
by codesnips 4 tabs
ruby
class Post < ApplicationRecord
  belongs_to :author, class_name: 'User'
  has_many :comments, dependent: :destroy

  scope :published, -> { where.not(published_at: nil).where('published_at <= ?', Time.current) }
  scope :draft, -> { where(published_at: nil) }

ActiveRecord scopes for reusable query logic

rails activerecord patterns
by Alex Kumar 1 tab
ruby
module Api
  module V1
    class UsersController < BaseController
      def show
        user = User.includes(:profile).find(params[:id])

ETags for conditional requests and caching

rails caching http-caching
by Alex Kumar 1 tab
ruby
class PostsController < ApplicationController
  def index
    @posts = Post.includes(:author)
                 .order(created_at: :desc)
                 .page(params[:page])
                 .per(10)

Turbo Frames: infinite scroll with lazy-loading frame

rails turbo hotwire
by codesnips 4 tabs
ruby
require "csv"

class PeopleCsvStream
  include Enumerable

  HEADERS = %w[id full_name email signed_up_at plan].freeze

Resilient CSV Export as a Streamed Response

rails performance streaming
by codesnips 3 tabs
erb
<form data-controller="query-sync" data-action="change->query-sync#apply">
  <select name="status" class="rounded border p-2">
    <option value="">Any</option>
    <option value="open">Open</option>
    <option value="closed">Closed</option>
  </select>

Filter UI that syncs query params via Stimulus (no front-end router)

rails hotwire stimulus
by Henry Kim 2 tabs

Share this code

Here's the card — post it anywhere.

Keep navbar state across Turbo navigations with data-turbo-permanent — share card
Link copied