Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 37 ยท Views and Templates

Hotwire: Turbo and Stimulus

Learn Hotwire in Rails: Turbo Drive, Turbo Frames, Turbo Streams and Stimulus controllers, with read-only Rails code and runnable Ruby stand-ins for frames and stream messages.

Rails apps can feel fast and interactive without a JavaScript framework. The default answer is Hotwire (HTML Over The Wire): the server keeps sending HTML, and a small JavaScript layer swaps pieces of the page instead of reloading all of it. Hotwire has two parts. Turbo updates the page from server-rendered HTML, and Stimulus adds small bits of behaviour to HTML elements.

Turbo and Stimulus are JavaScript libraries that ship with new Rails apps, so the code here is read-only. To see the ideas run, the stand-ins reproduce the server side in plain Ruby: a frame replacement and the <turbo-stream> messages a controller sends.

Turbo Drive: faster navigation for free

Turbo Drive is on by default. It intercepts link clicks and form submits, fetches the next page in the background, and swaps the <body> while keeping the <head> and the JavaScript state. You write normal Rails links and forms and the app simply feels like a single-page application.

Because forms are submitted with fetch, Turbo expects specific status codes. After a failed validation, render the form again with status: :unprocessable_entity (422), and after success, redirect:

Ruby
# read-only
def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to @article, notice: "Saved."
  else
    render :new, status: :unprocessable_entity   # Turbo needs the 422
  end
end

To opt out for one link, use data: { turbo: false }. For non-GET links, the helper option is data: { turbo_method: :delete }, as you saw in view helpers.

Turbo Frames: update one region

A frame is a <turbo-frame id="..."> element. A link or form inside a frame only replaces the frame with the matching id from the response; the rest of the page stays put.

ERB
<%# read-only: articles/show.html.erb %>
<h1><%= @article.title %></h1>

<%= turbo_frame_tag dom_id(@article, :body) do %>
  <p><%= @article.body %></p>
  <%= link_to "Edit", edit_article_path(@article) %>
<% end %>
ERB
<%# read-only: articles/edit.html.erb %>
<%= turbo_frame_tag dom_id(@article, :body) do %>
  <%= render "form", article: @article %>
<% end %>

Clicking "Edit" fetches the edit page, Turbo finds the frame with the same id in the response, and swaps only that part. The server did nothing special; it rendered a normal page. dom_id(@article, :body) produces a stable id like body_article_7.

Other frame features worth knowing: src: loads a frame lazily, loading: :lazy waits until it scrolls into view, and data: { turbo_frame: "_top" } makes a link inside a frame navigate the whole page.

Stand-in: how a frame is swapped

This stand-in does what the browser-side Turbo does, in Ruby: it finds a frame by id in the old page and replaces its content with the same frame from the response.

Ruby Stand-in: replacing a turbo-frame by id

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The footer and heading are untouched, and if the response has no matching frame, nothing changes (real Turbo shows a "Content missing" message in that case).

Turbo Streams: change several places at once

A Turbo Stream is a short HTML snippet that says "do this to that element". Actions include append, prepend, replace, update, remove, before and after. A controller can answer a form submit with streams, so one request updates the list, a counter and a flash message together.

ERB
<%# read-only: app/views/comments/create.turbo_stream.erb %>
<%= turbo_stream.append "comments", partial: "comments/comment", locals: { comment: @comment } %>
<%= turbo_stream.update "comment_count", @article.comments.count %>
<%= turbo_stream.replace "new_comment", partial: "comments/form", locals: { comment: Comment.new } %>
Ruby
# read-only: the controller
def create
  @comment = @article.comments.build(comment_params)
  respond_to do |format|
    if @comment.save
      format.turbo_stream
      format.html { redirect_to @article }
    else
      format.html { render "articles/show", status: :unprocessable_entity }
    end
  end
end

Always keep an html fallback so the page still works without JavaScript. Streams can also be pushed over WebSockets with broadcast_* methods on models, so other users' pages update live (this uses Action Cable and Solid Cable or Redis).

Stand-in: generating stream messages

Ruby Stand-in: building turbo-stream elements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The response has content type text/vnd.turbo-stream.html. Turbo applies each element in order. Notice that the user text is escaped before it goes into the stream, exactly as in a normal template.

Stimulus: a little JavaScript, attached to HTML

When you need real client-side behaviour (a character counter, a dropdown, a copy button), use Stimulus. A Stimulus controller is a small class connected to HTML through data- attributes:

ERB
<%# read-only %>
<div data-controller="counter">
  <textarea data-counter-target="input" data-action="input->counter#update"></textarea>
  <span data-counter-target="output">0</span> characters
</div>
JavaScript
// read-only: app/javascript/controllers/counter_controller.js
import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["input", "output"]

  update() {
    this.outputTarget.textContent = this.inputTarget.value.length
  }
}

The HTML stays the source of truth: data-controller names the class, data-*-target marks elements, and data-action wires events. Stimulus works with Turbo because it watches the DOM, so controllers connect automatically to HTML that Turbo inserts.

Turbo, Stimulus and importmap are JavaScript, so you need a browser to run them. You can try them in the HTML and JavaScript tutorials on this site; the idea of "server returns HTML, client swaps it" is easy to simulate there.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does Turbo Drive do by default?

    Turbo Drive intercepts links and forms and swaps the body, which makes navigation faster.
  2. 2. A link inside a Turbo Frame is clicked. What gets replaced?

    Turbo looks for a frame with the same id in the response and swaps just that region.
  3. 3. Which status should you use when rendering a form again after failed validation so Turbo shows it?

    Turbo only renders form responses with error statuses like 422; a 200 is ignored for form submissions.
  4. 4. What is a Turbo Stream?

    Streams are small HTML messages that tell Turbo which element to change and how.

Summary

  • Hotwire sends HTML from the server and swaps parts of the page; Turbo and Stimulus are its two halves.
  • Turbo Drive speeds up navigation; render failed forms with status 422 and redirect on success.
  • Turbo Frames swap one matching <turbo-frame> region; Turbo Streams run actions such as append, update and remove on elements by id.
  • Stimulus controllers attach small behaviours through data-controller, data-*-target and data-action.
  • Always provide an HTML fallback so the page works without JavaScript.

Next: Active Record: Models and Databases