Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
Turbo
https://turbo.hotwired.dev/
Admin
Turbo delivers single-page web application speed without writing JavaScript by using
...
Tokens:
18,842
Snippets:
241
Trust Score:
9.3
Update:
1 month ago
Context
Chat
Benchmark
81.25
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Turbo Frame with Recurse Example Source: https://turbo.hotwired.dev/reference/frames Demonstrates the use of the 'recurse' attribute to load nested frames. This is useful when the target frame is not directly in the response but can be loaded via an intermediate frame. ```html <turbo-frame id="recursive" recurse="composer" src="recursive.html"> </turbo-frame> ``` ```html <turbo-frame id="recursive"> <turbo-frame id="composer"> <a href="frames.html">Link</a> </turbo-frame> </turbo-frame> ``` -------------------------------- ### Turbo Stream Response Example Source: https://turbo.hotwired.dev/handbook/streams.html This is an example of the `text/vnd.turbo-stream.html` response format. It instructs the client to append a new message, rendered using a server-side partial, to the element with the ID `messages`. ```html Content-Type: text/vnd.turbo-stream.html; charset=utf-8 <turbo-stream action="append" target="messages"> <template> <div id="message_1"> The content of the message. </div> </template> </turbo-stream> ``` -------------------------------- ### Perform Visits with Different HTTP Methods Source: https://turbo.hotwired.dev/handbook/drive.html Change the HTTP method for a Turbo visit by adding the `data-turbo-method` attribute to a link. This example shows how to use it for a DELETE request. ```html <a href="/articles/54" data-turbo-method="delete">Delete the article</a> ``` -------------------------------- ### Identifying Preloaded Requests Source: https://turbo.hotwired.dev/handbook/drive.html Listen for `turbo:before-fetch-request` events and check the `X-Sec-Purpose` header to distinguish preloaded requests from others. This allows for conditional setup based on the request's origin. ```javascript addEventListener("turbo:before-fetch-request", (event) => { if (event.detail.fetchOptions.headers["X-Sec-Purpose"] === "prefetch") { // do additional preloading setup… } else { // do something else… } }) ``` -------------------------------- ### CSRF Meta Tag Example Source: https://turbo.hotwired.dev/handbook/frames.html Example of a meta tag used for CSRF protection. The token will be automatically added to request headers. ```html <meta name="csrf-token" content="[your-token]"> ``` -------------------------------- ### Response for Eager Loaded Frame Source: https://turbo.hotwired.dev/handbook/frames.html The response from an eager-loaded frame's `src` must contain a corresponding `<turbo-frame>` element. This example shows the content returned for the `set_aside_tray` frame. ```html <body> <h1>Set Aside Emails</h1> <p>These are emails you've set aside</p> <turbo-frame id="set_aside_tray"> <div id="emails"> <div id="email_1"> <a href="/emails/1">My important email</a> </div> </div> </turbo-frame> </body> ``` -------------------------------- ### Turbo Frame Update Example Source: https://turbo.hotwired.dev/handbook/frames.html Illustrates a server response containing an updated Turbo Frame. Only the content within the matching `<turbo-frame>` ID is extracted and used to replace the existing frame content. ```html <body> <h1>Editing message</h1> <turbo-frame id="message_1"> <form action="/messages/1"> <input name="message[name]" type="text" value="My message title"> <textarea name="message[content]">My message content</textarea> <input type="submit"> </form> </turbo-frame> </body> ``` -------------------------------- ### Pause Rendering for Animations Source: https://turbo.hotwired.dev/handbook/drive.html Pause rendering before it starts by calling `event.preventDefault()` on `turbo:before-render`. Resume rendering after asynchronous operations like animations complete by calling `event.detail.resume()`. ```javascript document.addEventListener("turbo:before-render", async (event) => { event.preventDefault() await animateOut() event.detail.resume() }) ``` -------------------------------- ### Customize Rendering with Idiomorph Source: https://turbo.hotwired.dev/handbook/drive.html Override the default rendering behavior by listening for the `turbo:before-render` event and providing a custom render function. This example uses Idiomorph to morph elements. ```javascript import { Idiomorph } from "idiomorph" addEventListener("turbo:before-render", (event) => { event.detail.render = (currentElement, newElement) => { Idiomorph.morph(currentElement, newElement) } }) ``` -------------------------------- ### Declare Custom Stream Actions Source: https://turbo.hotwired.dev/handbook/streams.html Define custom stream actions directly on the `StreamActions` object for simpler integration. This example shows how to add a 'log' action that logs a message attribute. ```javascript import { StreamActions } from "@hotwired/turbo" // <turbo-stream action="log" message="Hello, world"></turbo-stream> // StreamActions.log = function () { console.log(this.getAttribute("message")) } ``` -------------------------------- ### Disable Form Fields on Submission Start Source: https://turbo.hotwired.dev/handbook/drive.html Listen for the turbo:submit-start event to disable all fields within the submitted form. This prevents user interaction with form elements during the submission process. ```javascript addEventListener("turbo:submit-start", ({ target }) => { for (const field of target.elements) { field.disabled = true } }) ``` -------------------------------- ### Observe Turbo Load Event for JavaScript Behavior Source: https://turbo.hotwired.dev/handbook/building Set up JavaScript behavior that should run after every Turbo Drive visit, including the initial page load. Be mindful of potential state cleanup from previous pages. ```javascript document.addEventListener("turbo:load", function() { // ... }) ``` -------------------------------- ### Eager Loading with Initial Content Source: https://turbo.hotwired.dev/handbook/frames.html Populate eager-loading frames with initial content, such as a loading spinner, which will be overwritten when the content is fetched from the `src`. ```html <turbo-frame id="set_aside_tray" src="/emails/set_aside"> <img src="/icons/spinner.gif"> </turbo-frame> ``` -------------------------------- ### Perform Application Visits with Turbo.visit Source: https://turbo.hotwired.dev/reference/drive Use Turbo.visit to navigate to a new location. You can specify an action like 'advance' or 'replace', or target a specific frame for navigation. ```javascript Turbo.visit(location) Turbo.visit(location, { action: action }) Turbo.visit(location, { frame: frame }) ``` -------------------------------- ### Import Turbo Functions via npm Source: https://turbo.hotwired.dev/handbook/installing Import specific Turbo functions like Turbo.visit() when you need to use them in your JavaScript code. ```javascript import * as Turbo from "@hotwired/turbo" ``` -------------------------------- ### Turbo Stream Actions: Replace and Update with Morph Source: https://turbo.hotwired.dev/handbook/streams.html Illustrates 'replace' and 'update' actions using the 'morph' method for smoother DOM transitions. 'Morph' allows for more efficient updates by comparing and updating only the necessary parts of the DOM. ```html <turbo-stream action="replace" method="morph" target="current_step"> <template> <!-- The contents of this template will replace the element with ID "current_step" via morph. --> <li>New item</li> </template> </turbo-stream> <turbo-stream action="update" method="morph" target="current_step"> <template> <!-- The contents of this template will replace the children of the element with ID "current_step" via morph. --> <li>New item</li> </template> </turbo-stream> ``` -------------------------------- ### Load Application JavaScript Bundle Source: https://turbo.hotwired.dev/handbook/building Ensure your application's JavaScript bundle is loaded in the `<head>` using a `<script>` element. This prevents Turbo Drive from reloading the bundle on every page change. ```html <head> ... <script src="/application-cbd3cd4.js" defer></script> </head> ``` -------------------------------- ### Turbo Stream Actions: Remove, Before, After Source: https://turbo.hotwired.dev/handbook/streams.html Shows the 'remove', 'before', and 'after' actions for DOM manipulation. 'Remove' deletes a target element. 'Before' and 'after' insert new content immediately preceding or following the target element, respectively. ```html <turbo-stream action="remove" target="message_1"> <!-- The element with DOM ID "message_1" will be removed. The contents of this stream element are ignored. --> </turbo-stream> <turbo-stream action="before" target="current_step"> <template> <!-- The contents of this template will be added before the the element with ID "current_step". --> <li>New item</li> </template> </turbo-stream> <turbo-stream action="after" target="current_step"> <template> <!-- The contents of this template will be added after the the element with ID "current_step". --> <li>New item</li> </template> </turbo-stream> ``` -------------------------------- ### Globally Disable Turbo Drive (Opt-in) Source: https://turbo.hotwired.dev/handbook/drive.html Set `Turbo.session.drive = false` to make Turbo Drive opt-in. In this mode, `data-turbo="true"` is used to enable Drive on a per-element basis. ```javascript import { Turbo } from "@hotwired/turbo-rails" Turbo.session.drive = false ``` -------------------------------- ### Turbo.visit Source: https://turbo.hotwired.dev/reference/drive Performs an Application Visit to a given location, optionally with an action or frame. ```APIDOC ## Turbo.visit ### Description Performs an Application Visit to the given _location_ (a string containing a URL or path) with the specified _action_ (a string, either `"advance"` or `"replace"`). If _location_ is a cross-origin URL, or falls outside of the specified root, Turbo performs a full page load. If _action_ is unspecified, Turbo Drive assumes a value of `"advance"`. If _frame_ is specified, navigate a `<turbo-frame>` element with a matching `[id]` to the provided _location_. ### Method `Turbo.visit(location)` `Turbo.visit(location, { action: action })` `Turbo.visit(location, { frame: frame })` ### Parameters #### Path Parameters - **location** (string) - Required - The URL or path to visit. - **action** (string) - Optional - The action to perform, either `"advance"` or `"replace"`. Defaults to `"advance"`. - **frame** (string) - Optional - The ID of the `<turbo-frame>` element to navigate. ``` -------------------------------- ### Enable View Transitions with Meta Tag Source: https://turbo.hotwired.dev/handbook/drive.html Turbo can trigger view transitions if the browser supports the View Transition API and both the current and next pages include the `<meta name="view-transition" content="same-origin" />` tag. ```html <meta name="view-transition" content="same-origin" /> ``` -------------------------------- ### Prepare Page Before Caching Source: https://turbo.hotwired.dev/handbook/building Listen for the `turbo:before-cache` event to reset forms, collapse UI elements, or tear down widgets before Turbo Drive caches the page. This ensures the page is ready for restoration. ```javascript document.addEventListener("turbo:before-cache", function() { // ... }) ``` -------------------------------- ### Turbo Stream Actions: Append, Prepend, Replace, Update Source: https://turbo.hotwired.dev/handbook/streams.html Demonstrates the 'append', 'prepend', 'replace', and 'update' actions for modifying DOM elements. Use 'append' and 'prepend' to add content to the beginning or end of a target. 'Replace' substitutes the entire target element, while 'update' modifies its inner HTML, retaining event handlers. ```html <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> <turbo-stream action="prepend" target="messages"> <template> <div id="message_1"> This div will be prepended to the element with the DOM ID "messages". </div> </template> </turbo-stream> <turbo-stream action="replace" target="message_1"> <template> <div id="message_1"> This div will replace the existing element with the DOM ID "message_1". </div> </template> </turbo-stream> <turbo-stream action="update" target="unread_count"> <template> <!-- The contents of this template will replace the contents of the element with ID "unread_count" by setting innerHtml to "" and then switching in the template contents. Any handlers bound to the element "unread_count" would be retained. This is to be contrasted with the "replace" action above, where that action would necessitate the rebuilding of handlers. --> 1 </template> </turbo-stream> ``` -------------------------------- ### Import Turbo for Side Effects via npm Source: https://turbo.hotwired.dev/handbook/installing Import the Turbo library without specific functions if you are not calling any Turbo functions directly. This helps with bundler tree-shaking. ```javascript import "@hotwired/turbo"; ``` -------------------------------- ### Set Turbo Drive Root Location Source: https://turbo.hotwired.dev/handbook/drive.html Scope Turbo Drive navigation to a specific path on the same origin by setting the `content` attribute of `<meta name="turbo-root">` to the desired root path. ```html <head> <!-- … --> <meta name="turbo-root" content="/app"> </head> ``` -------------------------------- ### Configure Form Confirmation Method Source: https://turbo.hotwired.dev/reference/drive Assign a confirmation method to Turbo.config.forms.confirm for links with data-turbo-confirm. The method should return a Promise that resolves to true or false. ```javascript Turbo.config.forms.confirm = confirmMethod ``` -------------------------------- ### Integrate JavaScript Behavior with Stimulus Source: https://turbo.hotwired.dev/handbook/building Use Stimulus controllers to manage JavaScript behavior for DOM elements, handling updates from Turbo Drive, Turbo Frames, and Turbo Streams automatically via MutationObserver. ```html <div data-controller="hello"> <input data-hello-target="name" type="text"> <button data-action="click->hello#greet">Greet</button> </div> ``` ```javascript // hello_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { greet() { console.log(`Hello, ${this.name}! `) } get name() { return this.targets.find("name").value } } ``` -------------------------------- ### Trigger Replace Visit Programmatically Source: https://turbo.hotwired.dev/handbook/drive.html Programmatically initiate a replace visit by passing the `action: "replace"` option to `Turbo.visit`. This updates the current history entry instead of adding a new one. ```javascript Turbo.visit("/edit", { action: "replace" }) ``` -------------------------------- ### Preload Links into Turbo Drive Cache Source: https://turbo.hotwired.dev/handbook/drive.html Use the `data-turbo-preload` attribute on anchor tags to preload pages into Turbo Drive's cache, making subsequent visits feel instantaneous. This is useful for critical application pages. ```html <a href="/important-page" data-turbo-preload> Important Page </a> ``` -------------------------------- ### Basic Turbo Frame Structure Source: https://turbo.hotwired.dev/handbook/frames.html Demonstrates the basic structure of a page with two Turbo Frames: one for a message and another for comments. Each frame has a unique ID for targeted updates. ```html <body> <div id="navigation">Links targeting the entire page</div> <turbo-frame id="message_1"> <h1>My message title</h1> <p>My message content</p> <a href="/messages/1/edit">Edit this message</a> </turbo-frame> <turbo-frame id="comments"> <div id="comment_1">One comment</div> <div id="comment_2">Two comments</div> <form action="/messages/comments">...</form> </turbo-frame> </body> ``` -------------------------------- ### Before Action Source: https://turbo.hotwired.dev/reference/streams Inserts content before the element specified by a target DOM ID. ```html <turbo-stream action="before" target="dom_id"> <template> Content to place before the element designated with the dom_id. </template> </turbo-stream> ``` -------------------------------- ### Turbo Frame with Deferred Loading Source: https://turbo.hotwired.dev/handbook/introduction Use the `src` attribute on a `<turbo-frame>` to defer loading its content. Turbo will fetch the content from the specified URL and replace the frame's placeholder. ```html <turbo-frame id="messages" src="/messages"> <p>This message will be replaced by the response from /messages.</p> </turbo-frame> ``` -------------------------------- ### Promoting Frame Navigation to a Page Visit Source: https://turbo.hotwired.dev/handbook/frames.html Use the `data-turbo-action="advance"` attribute on a turbo-frame or its descendant navigation elements to promote frame navigations to full page visits. This updates both the frame's content and the browser's history. ```html <turbo-frame id="articles" data-turbo-action="advance"> <a href="/articles?page=2" rel="next">Next page</a> </turbo-frame> ``` -------------------------------- ### Configure Progress Bar Delay Source: https://turbo.hotwired.dev/reference/drive Set Turbo.config.drive.progressBarDelay to control the delay in milliseconds before the progress bar appears during navigation. The default is 500ms. ```javascript Turbo.config.drive.progressBarDelay = delayInMilliseconds ``` -------------------------------- ### Turbo Stream Actions with Multiple Targets Source: https://turbo.hotwired.dev/handbook/streams.html Illustrates using the 'targets' attribute with a CSS selector to apply actions to multiple elements simultaneously. This is useful for batch operations like removing multiple records or validating several fields. ```html <turbo-stream action="remove" targets=".old_records"> <!-- The element with the class "old_records" will be removed. The contents of this stream element are ignored. --> </turbo-stream> <turbo-stream action="after" targets="input.invalid_field"> <template> <!-- The contents of this template will be added after the all elements that match "inputs.invalid_field". --> <span>Incorrect</span> </template> </turbo-stream> ``` -------------------------------- ### Basic Turbo Frame for Form Submission Source: https://turbo.hotwired.dev/handbook/introduction Wrap a form within a `<turbo-frame>` to scope its navigation. Submissions within this frame will update only the frame's content. ```html <turbo-frame id="new_message"> <form action="/messages" method="post"> ... </form> </turbo-frame> ``` -------------------------------- ### Include Turbo via CDN Script Tag Source: https://turbo.hotwired.dev/handbook/installing Add this script tag to the <head> of your HTML to use the latest compiled version of Turbo. ```html <head> <script type="module" src="https://cdn.jsdelivr.net/npm/@hotwired/turbo@latest/dist/turbo.es2017-esm.min.js"></script> </head> ``` -------------------------------- ### Trigger Replace Visit with Link Source: https://turbo.hotwired.dev/handbook/drive.html Annotate a link with `data-turbo-action="replace"` to trigger a replace visit, which updates the history stack without pushing a new entry. ```html <a href="/edit" data-turbo-action="replace">Edit</a> ``` -------------------------------- ### Customize View Transition Animations Source: https://turbo.hotwired.dev/handbook/drive.html Use the `data-turbo-visit-direction` attribute added to the `<html>` element to apply custom CSS animations for different transition directions (forward, back, none). ```css html[data-turbo-visit-direction="forward"]::view-transition-old(sidebar):only-child { animation: slide-to-right 0.5s ease-out; } ``` -------------------------------- ### Dynamically Remove Assets Source: https://turbo.hotwired.dev/handbook/drive.html Instruct Turbo Drive to dynamically remove CSS stylesheets or style elements when they are not present in a navigation response using `data-turbo-track="dynamic"`. This avoids full reloads for style-only changes. ```html <head> <!-- … --> <link rel="stylesheet" href="/page-specific-styles-258e88d.css" data-turbo-track="dynamic"> <style data-turbo-track="dynamic"> .page-specific-styles { /* … */ } </style> </head> ``` -------------------------------- ### Custom Turbo Frame Rendering with Morphdom Source: https://turbo.hotwired.dev/handbook/frames.html Customize Turbo Frame rendering by overriding the default process with morphdom for element updates. Attach the listener to the document to affect all frames. ```javascript import morphdom from "morphdom" addEventListener("turbo:before-frame-render", (event) => { event.detail.render = (currentElement, newElement) => { morphdom(currentElement, newElement, { childrenOnly: true }) } }) ``` -------------------------------- ### Detect Preview Visibility Source: https://turbo.hotwired.dev/handbook/building Check for the `data-turbo-preview` attribute on the `<html>` element to determine if Turbo Drive is displaying a preview from cache. This allows for selective behavior enablement or disablement when a preview is visible. ```javascript if (document.documentElement.hasAttribute("data-turbo-preview")) { // Turbo Drive is displaying a preview } ``` -------------------------------- ### Turbo.config.forms.confirm Source: https://turbo.hotwired.dev/reference/drive Sets the method that is called by links decorated with data-turbo-confirm. ```APIDOC ## Turbo.config.forms.confirm ### Description Sets the method that is called by links decorated with `data-turbo-confirm`. The default is the browser’s built in `confirm`. The method should return a `Promise` object that resolves to true or false, depending on whether the visit should proceed. ### Method `Turbo.config.forms.confirm = confirmMethod` ### Parameters #### Path Parameters - **confirmMethod** (function) - Required - The confirmation method to be called. ``` -------------------------------- ### Turbo Frame with Overwritten Navigation Targets Source: https://turbo.hotwired.dev/reference/frames A turbo-frame demonstrating how to overwrite default navigation targets. Links and forms can be configured to either replace the current frame or the entire page. ```html <turbo-frame id="messages"> <a href="/messages/1"> Following link will replace this frame. </a> <a href="/messages/1" data-turbo-frame="_top"> Following link will replace the whole page, not this frame. </a> <form action="/messages" data-turbo-frame="navigation"> Submitting form will replace the navigation frame. </form> </turbo-frame> ``` -------------------------------- ### Turbo.config.drive.progressBarDelay Source: https://turbo.hotwired.dev/reference/drive Sets the delay after which the progress bar will appear during navigation. ```APIDOC ## Turbo.config.drive.progressBarDelay ### Description Sets the delay after which the progress bar will appear during navigation, in milliseconds. The progress bar appears after 500ms by default. Note that this method has no effect when used with the iOS or Android adapters. ### Method `Turbo.config.drive.progressBarDelay = delayInMilliseconds` ### Parameters #### Path Parameters - **delayInMilliseconds** (number) - Required - The delay in milliseconds. ``` -------------------------------- ### Replace Element with Turbo Streams Source: https://turbo.hotwired.dev/handbook/introduction Replaces an existing element with new content. Use this to update specific parts of the page. ```html <turbo-stream action="replace" target="message_1"> <template> <div id="message_1">This changes the existing message!</div> </template> </turbo-stream> ``` -------------------------------- ### After Action Source: https://turbo.hotwired.dev/reference/streams Inserts content after the element specified by a target DOM ID. ```html <turbo-stream action="after" target="dom_id"> <template> Content to place after the element designated with the dom_id. </template> </turbo-stream> ``` -------------------------------- ### Forcing a Full Page Reload on Frame Navigation Source: https://turbo.hotwired.dev/handbook/frames.html Include the `<meta name="turbo-visit-control" content="reload">` tag in the `<head>` to ensure that any navigation originating from within a frame results in a full page reload. This is particularly useful for handling session expirations or redirects to login pages. ```html <head> <meta name="turbo-visit-control" content="reload"> ... </head> ``` -------------------------------- ### Track Asset Changes for Reload Source: https://turbo.hotwired.dev/handbook/drive.html Configure CSS and JavaScript assets to trigger a full page reload when they change by using the `data-turbo-track="reload"` attribute. Include a version identifier in asset URLs. ```html <head> <!-- … --> <link rel="stylesheet" href="/application-258e88d.css" data-turbo-track="reload"> <script src="/application-cbd3cd4.js" data-turbo-track="reload"></script> </head> ``` -------------------------------- ### Pause Requests for Header Injection Source: https://turbo.hotwired.dev/handbook/drive.html Intercept requests before they are sent by listening for `turbo:before-fetch-request`. Pause the request with `event.preventDefault()`, modify `fetchOptions.headers`, and then resume the request. ```javascript document.addEventListener("turbo:before-fetch-request", async (event) => { event.preventDefault() const token = await getSessionToken(window.app) event.detail.fetchOptions.headers["Authorization"] = `Bearer ${token}` event.detail.resume() }) ``` -------------------------------- ### Turbo Stream Action: Refresh Source: https://turbo.hotwired.dev/handbook/streams.html Demonstrates the 'refresh' action, which can be used to trigger a full page refresh or re-fetch resources. It requires a 'request-id' attribute. ```html <turbo-stream action="refresh" request-id="abcd-1234"></turbo-stream> ``` -------------------------------- ### Rails Controller for Creating and Appending Messages Source: https://turbo.hotwired.dev/handbook/streams.html This Rails controller action handles the creation of a new message and responds with a Turbo Stream to append it to the existing list. It reuses the `_message.html.erb` partial. ```ruby # app/controllers/messages_controller.rb class MessagesController < ApplicationController def index @messages = Message.all end def create message = Message.create!(params.require(:message).permit(:content)) respond_to do |format| format.turbo_stream do render turbo_stream: turbo_stream.append(:messages, partial: "messages/message", locals: { message: message }) end format.html { redirect_to messages_url } end end end ``` -------------------------------- ### Turbo.session.drive Source: https://turbo.hotwired.dev/reference/drive Turns Turbo Drive off by default, requiring opt-in via data-turbo="true". ```APIDOC ## Turbo.session.drive ### Description Turns Turbo Drive off by default. You must now opt-in to Turbo Drive on a per-link and per-form basis using `data-turbo="true"`. ### Method `Turbo.session.drive = false` ``` -------------------------------- ### Eager Loading Turbo Frames Source: https://turbo.hotwired.dev/handbook/frames.html Use the `src` attribute on a `turbo-frame` tag to automatically load content when the tag appears on the page. This is useful for loading secondary content like trays or sidebars. ```html <body> <h1>Imbox</h1> <div id="emails"> ... </div> <turbo-frame id="set_aside_tray" src="/emails/set_aside"> </turbo-frame> <turbo-frame id="reply_later_tray" src="/emails/reply_later"> </turbo-frame> </body> ``` -------------------------------- ### Prepend Action Source: https://turbo.hotwired.dev/reference/streams Prepends content to a container specified by a target DOM ID. If the template's first element ID already exists in the container, it will be replaced instead of prepended. ```html <turbo-stream action="prepend" target="dom_id"> <template> Content to prepend to container designated with the dom_id. </template> </turbo-stream> ``` -------------------------------- ### Force Full Reload for Specific Pages Source: https://turbo.hotwired.dev/handbook/drive.html Ensure that visits to a particular page always trigger a full browser reload by including a `<meta name="turbo-visit-control" content="reload">` tag in the page's head. ```html <head> <!-- … --> <meta name="turbo-visit-control" content="reload"> </head> ``` -------------------------------- ### Rails Controller Responding to Turbo Streams Source: https://turbo.hotwired.dev/handbook/streams.html This Rails controller action demonstrates how to respond to a Turbo Streams request by rendering a Turbo Stream or falling back to an HTML redirect. It's used for actions like destroying a record. ```ruby def destroy @message = Message.find(params[:id]) @message.destroy respond_to do |format| format.turbo_stream { render turbo_stream: turbo_stream.remove(@message) } format.html { redirect_to messages_url } end end ``` -------------------------------- ### Rails View Partials for Reusable Templates Source: https://turbo.hotwired.dev/handbook/streams.html These Rails view partials show how server-side templates can be reused for both initial page loads and dynamic Turbo Stream updates. The `_message.html.erb` partial renders a single message, and `index.html.erb` renders a collection. ```html <!-- app/views/messages/_message.html.erb --> <div id="<%= dom_id message %>"> <%= message.content %> </div> ``` ```html <!-- app/views/messages/index.html.erb --> <h1>All the messages</h1> <%= render partial: "messages/message", collection: @messages %> ``` -------------------------------- ### Turbo.cache.clear Source: https://turbo.hotwired.dev/reference/drive Removes all entries from the Turbo Drive page cache. ```APIDOC ## Turbo.cache.clear ### Description Removes all entries from the Turbo Drive page cache. Call this when state has changed on the server that may affect cached pages. ### Method `Turbo.cache.clear()` ``` -------------------------------- ### Rails Model for Broadcasting Refreshes Source: https://turbo.hotwired.dev/handbook/page_refreshes.html In Rails, use `broadcasts_refreshes` in the model to enable broadcasting page refreshes. Ensure `turbo_stream_from` is present in the view. ```ruby # In the model class Calendar < ApplicationRecord broadcasts_refreshes end # View turbo_stream_from @calendar ``` -------------------------------- ### Controlling Frame Navigation with data-turbo-frame Source: https://turbo.hotwired.dev/handbook/frames.html Use the `data-turbo-frame` attribute on anchor tags or form elements to explicitly control where navigation initiated within a frame should occur. This allows for mixed navigation behaviors within a single frame context. ```html <body> <turbo-frame id="message_1"> ... <a href="/messages/1/edit"> Edit this message (within the current frame) </a> <a href="/messages/1/permission" data-turbo-frame="_top"> Change permissions (replace the whole page) </a> </turbo-frame> <form action="/messages/1/delete" data-turbo-frame="message_1"> <a href="/messages/1/warning" data-turbo-frame="_self"> Load warning within current frame </a> <input type="submit" value="Delete this message"> (with a confirmation shown in a specific frame) </form> </body> ``` -------------------------------- ### Require Confirmation for Visits Source: https://turbo.hotwired.dev/handbook/drive.html Add the `data-turbo-confirm` attribute to links or forms to prompt the user for confirmation before proceeding with a visit. This is often used with `data-turbo-method` for destructive actions. ```html <a href="/articles" data-turbo-method="get" data-turbo-confirm="Do you want to leave this page?">Back to articles</a> <a href="/articles/54" data-turbo-method="delete" data-turbo-confirm="Are you sure you want to delete the article?">Delete the article</a> ``` -------------------------------- ### Replace Action Source: https://turbo.hotwired.dev/reference/streams Replaces the element specified by a target DOM ID with new content. ```html <turbo-stream action="replace" target="dom_id"> <template> Content to replace the element designated with the dom_id. </template> </turbo-stream> ``` -------------------------------- ### Broadcast Page Refresh with Turbo Stream Source: https://turbo.hotwired.dev/handbook/page_refreshes.html Use the `refresh` turbo stream action to trigger a page refresh. The `method` and `scroll` attributes can specify the refresh behavior. ```html <turbo-stream action="refresh"></turbo-stream> ``` -------------------------------- ### Targeting Multiple Elements with After Source: https://turbo.hotwired.dev/reference/streams Inserts content after multiple elements matching a CSS query selector using the 'targets' attribute. ```html <turbo-stream action="after" targets=".elementsWithClass"> <template> Content to place after the elements designated with the css query. </template> </turbo-stream> ``` -------------------------------- ### Define Morphing Regions with Turbo Frames Source: https://turbo.hotwired.dev/handbook/page_refreshes.html Use a turbo frame with the `refresh="morph"` attribute to define regions that will reload and morph during a page refresh. This allows for loading additional content within specific frame areas. ```html <turbo-frame id="my-frame" refresh="morph" src="/my_frame"> </turbo-frame> ``` -------------------------------- ### Handled Form Submissions with Dots Source: https://turbo.hotwired.dev/handbook/drive.html Forms targeting paths that are explicitly handled by Turbo, even if they contain dots. This includes paths with trailing slashes or specific file extensions like `/messages.php` or `/messages.json/`. ```html <form action="/messages/67" method="post"> <!-- handled --> </form> <form action="/messages.67/action" method="post"> <!-- also handled --> </form> <form action="/messages.php" method="post" data-turbo="true"> <!-- also handled --> </form> <form action="/messages.json/" method="post" data-turbo="true"> <!-- also handled --> </form> <form action="/messages.json/123" method="post" data-turbo="true"> <!-- also handled --> </form> ``` -------------------------------- ### Control Caching with Client-Side API Source: https://turbo.hotwired.dev/handbook/building Manage page caching directives directly from JavaScript using `Turbo.cache` methods. These functions will add the meta tag if it's not present. ```javascript // Set cache control of current page to `no-cache` Turbo.cache.exemptPageFromCache() // Set cache control of current page to `no-preview` Turbo.cache.exemptPageFromPreview() ``` ```javascript Turbo.cache.resetCacheControl() ``` -------------------------------- ### Programmatically Prevent Prefetching with JavaScript Source: https://turbo.hotwired.dev/handbook/drive.html Intercept the `turbo:before-prefetch` event to programmatically prevent prefetching based on custom conditions, such as slow internet connections or ongoing data saving operations. ```javascript document.addEventListener("turbo:before-prefetch", (event) => { if (isSavingData() || hasSlowInternet()) { event.preventDefault() } }) function isSavingData() { return navigator.connection?.saveData } function hasSlowInternet() { return navigator.connection?.effectiveType === "slow-2g" || navigator.connection?.effectiveType === "2g" } ``` -------------------------------- ### Update Action Source: https://turbo.hotwired.dev/reference/streams Updates the content within a container specified by a target DOM ID. ```html <turbo-stream action="update" target="dom_id"> <template> Content to update to container designated with the dom_id. </template> </turbo-stream> ``` -------------------------------- ### Specify Refresh Method and Scroll Behavior in Turbo Stream Source: https://turbo.hotwired.dev/handbook/page_refreshes.html Customize page refresh behavior by specifying `method` (morph or replace) and `scroll` (preserve or reset) attributes within a `refresh` turbo stream action. ```html <turbo-stream action="refresh" method="morph" scroll="preserve"></turbo-stream> ``` -------------------------------- ### Configure Morphing for Page Refreshes Source: https://turbo.hotwired.dev/handbook/page_refreshes.html Use this meta tag in the page's head to enable morphing for page refreshes. This updates only changed DOM elements instead of replacing the entire body. ```html <head> ... <meta name="turbo-refresh-method" content="morph"> </head> ``` -------------------------------- ### Disable Turbo Drive Session Source: https://turbo.hotwired.dev/reference/drive Set Turbo.session.drive to false to disable Turbo Drive by default. Users will then need to opt-in using data-turbo="true" for specific links and forms. ```javascript Turbo.session.drive = false ``` -------------------------------- ### Disable Turbo Prefetching Globally Source: https://turbo.hotwired.dev/handbook/drive.html Disable prefetching for all links on the page by adding a meta tag to the head of your HTML document. ```html <meta name="turbo-prefetch" content="false"> ``` -------------------------------- ### Disable Prefetching on Specific Links or Elements Source: https://turbo.hotwired.dev/handbook/drive.html Control prefetching on a per-element basis by using the `data-turbo-prefetch="false"` attribute. This can be applied to individual links or parent elements to disable prefetching for their descendants. ```html <html> <head> <meta name="turbo-prefetch" content="true"> </head> <body> <a href="/articles">Articles</a> <!-- This link is prefetched --> <a href="/about" data-turbo-prefetch="false">About</a> <!-- Not prefetched --> <div data-turbo-prefetch="false"> <!-- Links inside this div will not be prefetched --> </div> </body> </html> ``` -------------------------------- ### Eager-loaded Turbo Frame Source: https://turbo.hotwired.dev/reference/frames An eager-loaded turbo-frame that loads its content from a remote src attribute upon initial rendering. The content is replaced once the src has been loaded. ```html <turbo-frame id="messages" src="/messages"> Content will be replaced when /messages has been loaded. </turbo-frame> ``` -------------------------------- ### Refresh Actions Source: https://turbo.hotwired.dev/reference/streams Initiates a page refresh. Can be debounced with a 'request-id' or configured with 'method' and 'scroll' attributes. ```html <!-- without `[request-id]` --> <turbo-stream action="refresh"></turbo-stream> <!-- debounced with `[request-id]` --> <turbo-stream action="refresh" request-id="abcd-1234"></turbo-stream> <!-- refresh behavior with `[method]` and `[scroll]` --> <turbo-stream action="refresh" method="morph" scroll="preserve"></turbo-stream> ``` -------------------------------- ### Enable Prefetching on Child Elements within a Disabled Parent Source: https://turbo.hotwired.dev/handbook/drive.html Override the disabled prefetching state of a parent element by explicitly enabling it on child elements using `data-turbo-prefetch="true"`. ```html <html> <body data-turbo-prefetch="false"> <nav id="header" data-turbo-prefetch="true"> <a href="/articles">Articles</a> <!-- This link is prefetched --> <a href="/about">About</a> <!-- This one as well --> </nav> <div id="body"> <!-- Links inside this div will not be prefetched --> </div> <footer id="footer" data-turbo-prefetch="true"> <!-- Links inside this footer will be prefetched --> </footer> </body> </html> ``` -------------------------------- ### Targeting Navigation to the Top Level Frame Source: https://turbo.hotwired.dev/handbook/frames.html Use the `target="_top"` attribute on a turbo-frame to ensure that links or form submissions within that frame navigate the entire page, rather than just the frame itself. This is useful for frames that should not contain their own navigation context. ```html <body> <h1>Imbox</h1> ... <turbo-frame id="set_aside_tray" src="/emails/set_aside" target="_top"> </turbo-frame> </body> ``` ```html <body> <h1>Set Aside Emails</h1> ... <turbo-frame id="set_aside_tray" target="_top"> ... </turbo-frame> </body> ``` -------------------------------- ### Marking an Element as Permanent Source: https://turbo.hotwired.dev/handbook/building Use the `data-turbo-permanent` attribute along with an `id` to designate an element that should persist across page loads. This preserves the element's state and event listeners. ```html <div id="cart-counter" data-turbo-permanent>1 item</div> ``` -------------------------------- ### Lazy-loaded Turbo Frame Source: https://turbo.hotwired.dev/reference/frames A lazy-loaded turbo-frame that defers loading its content from the src attribute until the frame becomes visible in the viewport. This is useful for improving initial page load performance. ```html <turbo-frame id="messages" src="/messages" loading="lazy"> Content will be replaced when the frame becomes visible and /messages has been loaded. </turbo-frame> ``` -------------------------------- ### Turbo Frame Promoting Navigations to Visits Source: https://turbo.hotwired.dev/reference/frames A turbo-frame that uses the data-turbo-action attribute to control navigation history. 'advance' adds a new entry, while 'replace' modifies the current history entry. ```html <turbo-frame id="messages" data-turbo-action="advance"> <a href="/messages?page=2">Advance history to next page</a> <a href="/messages?page=2" data-turbo-action="replace">Replace history with next page</a> </turbo-frame> ```