<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>
☰
</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>
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = ["menu", "link"]
static values = { menuOpen: Boolean }
connect() {
this.boundClose = this.closeOnNavigate.bind(this)
this.boundHighlight = this.highlightCurrent.bind(this)
document.addEventListener("turbo:before-render", this.boundClose)
document.addEventListener("turbo:load", this.boundHighlight)
this.highlightCurrent()
}
disconnect() {
document.removeEventListener("turbo:before-render", this.boundClose)
document.removeEventListener("turbo:load", this.boundHighlight)
}
toggle() {
this.menuOpenValue = !this.menuOpenValue
}
menuOpenValueChanged(open) {
this.menuTarget.classList.toggle("is-open", open)
const button = this.element.querySelector(".navbar-toggle")
if (button) button.setAttribute("aria-expanded", String(open))
}
closeOnNavigate() {
this.menuOpenValue = false
}
highlightCurrent() {
const path = window.location.pathname
this.linkTargets.forEach((link) => {
const active = new URL(link.href).pathname === path
link.classList.toggle("active", active)
})
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title><%= content_for(:title) || "Acme" %></title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag "application", "data-turbo-track": "reload" %>
<%= javascript_importmap_tags %>
</head>
<body>
<%= render "shared/navbar" %>
<main class="page">
<% if notice.present? %>
<div class="flash" data-controller="flash"><%= notice %></div>
<% end %>
<%= yield %>
</main>
</body>
</html>
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
class CommentsController < ApplicationController
before_action :set_post
def create
@comment = @post.comments.build(comment_params)
System test: asserting Turbo Stream responses
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
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
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
require "csv"
class PeopleCsvStream
include Enumerable
HEADERS = %w[id full_name email signed_up_at plan].freeze
Resilient CSV Export as a Streamed Response
<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)
Share this code
Here's the card — post it anywhere.