### 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
The content of the message.
```
--------------------------------
### 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
Delete the article
```
--------------------------------
### 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
```
--------------------------------
### 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 `` element. This example shows the content returned for the `set_aside_tray` frame.
```html
```
--------------------------------
### 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 `` ID is extracted and used to replace the existing frame content.
```html
Editing message
```
--------------------------------
### 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)
}
})
```
--------------------------------
### 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()
})
```
--------------------------------
### 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"
//
//
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
```
--------------------------------
### 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
New item
New item
```
--------------------------------
### Load Application JavaScript Bundle
Source: https://turbo.hotwired.dev/handbook/building
Ensure your application's JavaScript bundle is loaded in the `` using a `
```
--------------------------------
### 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
New item
New item
```
--------------------------------
### 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
```
--------------------------------
### 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 `` tag.
```html
```
--------------------------------
### 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
This div will be appended to the element with the DOM ID "messages".
This div will be prepended to the element with the DOM ID "messages".
This div will replace the existing element with the DOM ID "message_1".
1
```
--------------------------------
### 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 `` to the desired root path.
```html
```
--------------------------------
### 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
```
```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
Important Page
```
--------------------------------
### 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
```
--------------------------------
### Turbo Frame with Deferred Loading
Source: https://turbo.hotwired.dev/handbook/introduction
Use the `src` attribute on a `` to defer loading its content. Turbo will fetch the content from the specified URL and replace the frame's placeholder.
```html
This message will be replaced by the response from /messages.
```
--------------------------------
### 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
Next page
```
--------------------------------
### 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
Incorrect
```
--------------------------------
### Basic Turbo Frame for Form Submission
Source: https://turbo.hotwired.dev/handbook/introduction
Wrap a form within a `` to scope its navigation. Submissions within this frame will update only the frame's content.
```html
```
--------------------------------
### Include Turbo via CDN Script Tag
Source: https://turbo.hotwired.dev/handbook/installing
Add this script tag to the of your HTML to use the latest compiled version of Turbo.
```html
```
--------------------------------
### 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
Edit
```
--------------------------------
### Customize View Transition Animations
Source: https://turbo.hotwired.dev/handbook/drive.html
Use the `data-turbo-visit-direction` attribute added to the `` 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
```
--------------------------------
### 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 `` 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
}
```
--------------------------------
### 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
This changes the existing message!
```
--------------------------------
### Forcing a Full Page Reload on Frame Navigation
Source: https://turbo.hotwired.dev/handbook/frames.html
Include the `` tag in the `` 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
...
```
--------------------------------
### 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
```
--------------------------------
### 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
```
--------------------------------
### 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
```
--------------------------------
### 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
Imbox
...
```
--------------------------------
### 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 `` tag in the page's head.
```html
```
--------------------------------
### 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
<%= message.content %>
```
```html
All the messages
<%= render partial: "messages/message", collection: @messages %>
```
--------------------------------
### Rails Model for Broadcasting Refreshes
Source: https://turbo.hotwired.dev/handbook/page_refreshes
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
...
Edit this message (within the current frame)
Change permissions (replace the whole page)
```
--------------------------------
### 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
Back to articlesDelete the article
```
--------------------------------
### Broadcast Page Refresh with Turbo Stream
Source: https://turbo.hotwired.dev/handbook/page_refreshes
Use the `refresh` turbo stream action to trigger a page refresh. The `method` and `scroll` attributes can specify the refresh behavior.
```html
```
--------------------------------
### Define Morphing Regions with Turbo Frames
Source: https://turbo.hotwired.dev/handbook/page_refreshes
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
```
--------------------------------
### 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
```
--------------------------------
### 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"
}
```
--------------------------------
### Specify Refresh Method and Scroll Behavior in Turbo Stream
Source: https://turbo.hotwired.dev/handbook/page_refreshes
Customize page refresh behavior by specifying `method` (morph or replace) and `scroll` (preserve or reset) attributes within a `refresh` turbo stream action.
```html
```
--------------------------------
### Configure Morphing for Page Refreshes
Source: https://turbo.hotwired.dev/handbook/page_refreshes
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
...
```
--------------------------------
### 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
```
--------------------------------
### 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
ArticlesAbout
```
--------------------------------
### 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
```
--------------------------------
### 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
Imbox
...
```
```html
Set Aside Emails
...
...
```
--------------------------------
### 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
1 item
```
--------------------------------
### Mark Temporary Elements for Removal
Source: https://turbo.hotwired.dev/handbook/building
Annotate temporary elements like flash messages or alerts with `data-turbo-temporary`. Turbo Drive will automatically remove these elements before caching the page, preventing them from being redisplayed undesirably.
```html
Your cart was updated!
...
```
--------------------------------
### Append Element with Turbo Streams
Source: https://turbo.hotwired.dev/handbook/introduction
Appends a new element to a specified target. Use this to add new content to the end of a list or container.
```html
My new message!
```
--------------------------------
### Pausing Turbo Frame Rendering for Animations
Source: https://turbo.hotwired.dev/handbook/frames.html
Pause Turbo Frame rendering using event.preventDefault() to perform actions like exit animations before resuming rendering with event.detail.resume().
```javascript
document.addEventListener("turbo:before-frame-render", async (event) => {
event.preventDefault()
await animateOut()
event.detail.resume()
})
```
--------------------------------
### Customize Turbo Drive Progress Bar
Source: https://turbo.hotwired.dev/handbook/drive.html
Override the default styles for the Turbo Drive progress bar to change its appearance. Ensure custom styles come after default styles.
```css
.turbo-progress-bar {
height: 5px;
background-color: green;
}
```
--------------------------------
### Override Turbo Streams Render Function
Source: https://turbo.hotwired.dev/handbook/streams.html
Extend Turbo Streams to support custom actions like 'alert' or 'log' by listening to the `turbo:before-stream-render` event and providing a custom render function.
```javascript
addEventListener("turbo:before-stream-render", ((event) => {
const fallbackToDefaultActions = event.detail.render
event.detail.render = function (streamElement) {
if (streamElement.action == "alert") {
// ...
} else if (streamElement.action == "log") {
// ...
} else {
fallbackToDefaultActions(streamElement)
}
}
}))
```
--------------------------------
### Re-enable Turbo Drive within Disabled Ancestor
Source: https://turbo.hotwired.dev/handbook/drive.html
If Turbo Drive is disabled on an ancestor element using `data-turbo="false"`, you can re-enable it for a specific child element by adding `data-turbo="true"`.
```html
```
--------------------------------
### Disable Page Caching with Meta Tag
Source: https://turbo.hotwired.dev/handbook/building
Use the `no-cache` directive in the meta tag to prevent a page from being cached entirely. This ensures the page is always fetched from the network.
```html
...
```
--------------------------------
### Exclude Sections from Morphing
Source: https://turbo.hotwired.dev/handbook/page_refreshes
Flag elements with `data-turbo-permanent` to prevent them from being morphed during page refreshes. This is useful for elements like open popovers that should persist.
```html
...
```
--------------------------------
### Ignored Form Submissions with Dots
Source: https://turbo.hotwired.dev/handbook/drive.html
Forms targeting paths with a dot in the last segment are ignored by Turbo unless they end in a specific file extension. This includes paths like `/messages.67` or `/messages.php.1`.
```html
```
--------------------------------
### Disable Turbo Drive Progress Bar
Source: https://turbo.hotwired.dev/handbook/drive.html
Completely hide the Turbo Drive progress bar by setting its visibility to hidden.
```css
.turbo-progress-bar {
visibility: hidden;
}
```
--------------------------------
### Disable Turbo Drive on Specific Elements
Source: https://turbo.hotwired.dev/handbook/drive.html
Prevent Turbo Drive from handling links or forms by adding the `data-turbo="false"` attribute to the element or an ancestor. This causes the browser to handle the interaction normally.
```html
Disabled
```
--------------------------------
### Configure Scroll Preservation for Page Refreshes
Source: https://turbo.hotwired.dev/handbook/page_refreshes
Use this meta tag in the page's head to preserve scroll position during page refreshes. This keeps the vertical and horizontal scroll intact.
```html
...
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.