Extending Our Page with Turbo Streams

Let's learn about Turbo Stream actions and how they can help us with HTML content placement.

Turbo Streams

Turbo Streams is the next step in using Turbo to make pages more dynamic without writing any custom JavaScript. It helps to think of this development process as a successive enhancement.

Let’s recap:

  • We started with a working page that needed to be more interactive.

  • We therefore added inline editing and more responsive updates to part of the page.

  • Now, we’ll add the ability to update multiple parts of a page from a request.

Turbo Streams allow us to send a defined amount of HTML content to the page and have that content replace or augment existing content in multiple designated locations on the page. It’s designed for exactly our kind of situation, where we want multiple parts of the page to update from a single request. Turbo Streams is also designed to work well with WebSockets using ActionCable, which we’ll talk about later in Immediate Communication with ActionCable.

A Turbo Stream is another custom HTML tag, <turbo-stream>, which has two attributes and a child tag of template. An HTTP response can contain any amount of Turbo Stream tags. Generically, a Turbo Stream element looks like this:

<turbo-stream action="<ACTION>" target="<TARGET>">

For the Turbo Stream to work, we need to specify the target, which is the DOM ID of the element of the page being changed, and the action, which specifies what to do with the incoming HTML.

Turbo Streams actions

There are five actions:

  • append: The body of the template is added at the end of the target, and the existing contents are maintained.

  • prepend: The body of the template is added at the beginning of the target, and the existing contents are maintained.

  • remove: The element with the target ID is removed. In this case, the Turbo Stream does not need to have any contents.

  • replace: The body of the template will replace the existing element with the target ID. Typically, the body of the template is a new element with the same ID.

  • update: The body of the template will replace the content of the target, but not the element itself.

When the Turbo Stream response is evaluated, each separate Turbo Stream element performs its action on its target.

Get hands-on with 1000+ tech skills courses.