Turbo Streams

Actions and Targets

An example on how turbo_stream is rendered:

= turbo_stream.append :messages, @message

Where :messsages is the target and @message renders the partial _message.html.haml. Then it is rendered to:

<turbo-stream action="append" target="messages">
    <div id="message_23">
      // This div will be append to element with id="messages"

7 possible Actions

  • APPEND: Appends template to target
  • PREPEND: Preppends template to target
  • REPLACE: Replaces the full target with template
  • UPDATE: Replaces the content of target with template
  • REMOVE: Removes target
  • BEFORE: Adding template before target element
  • AFTER: Adding template after target

Streaming from HTTP responses

In rails controller streams will be rendered like:

def create
  @message = Message.find(....)
  respond_to do |format|
    format.turbo_stream # renders template in: create.turbo_stream.haml
    format.html { redirect_to messages_url }

Reusing server side templates inline:

  format.turbo_stream do
    render turbo_stream: turbo_stream.append(:messages, 
                partial: "messages/message", locals: { message: @message})

Both “partial:” and “locals:” can be replaced by @message (Great Rails code!!!).

Some notes

RECOMENDATION: Good practice is design without Streams, then in poor connections or server issues, when web sockets are broken, it will run anyway. Like a browser without JavaScript.
NOTE FOR BROWSER CACHE: Attribute “data-turbo-permanent” makes element alwaiys the samen in browser cache.

Leave a Reply

Your email address will not be published. Required fields are marked *