Using Turbo Streams, you can send snippets of HTML content to the page and replace or modify the existing content on the page. It's specifically designed for the situations where we want to update multiple parts of the page in response to a single request.
Turbo Streams deliver page changes as fragments of HTML wrapped in
<turbo-stream>
tags. Each stream element specifies an action together with a target ID to declare what should happen to the HTML inside it.
Turbo streams also work great with WebSockets, but we can ignore it for now.
In its essence, a Turbo Stream is HTML content wrapped in the <turbo-stream>
tag as well as a <template>
tag. The <turbo-stream>
tag also contains an action
and a target
attribute. The action
attribute instructs the Turbo framework what to do with this snippet, and the target
attribute helps Turbo find the elements with the given ID it should affect.
Here's a Turbo Stream that will be appended to a div
element with the messages
ID.
<turbo-stream action="append" target="messages">
<template>
<div id="message_1">
This div will be appended to the element with the DOM ID "messages".
</div>
</template>
</turbo-stream>
In addition to append
, there are six other actions.
append
: stream element is appended to the target.prepend
: stream element is prepended to the target.replace
: stream element replaces the target.update
: similar to replace, but replaces the inner content of the target, not the target itself.remove
: remove the target element (this stream doesn't contain any content)before
: contents of the stream are added before the targetafter
: contents of the stream are added after the target.
You can render any number of stream elements in a single stream message from a WebSocket, SSE or in response to a form submission.
If this is confusing, don't worry. Everything will make sense once we look at some real projects.