Basics of developing with Turbo Frames in web applications...
Turbo Frames decompose pages into independent segments that scope navigation. Clicking links or submitting forms inside a <turbo-frame> only updates that frame, keeping the rest of the page intact.
Use the <x-turbo::frame> Blade component to render a <turbo-frame> element:
@verbatim
@endverbatim
:id PropThe :id prop accepts multiple formats and auto-generates DOM IDs:
@verbatim
{{-- Model instance: generates dom_id($post) e.g. "post_1" --}} <x-turbo::frame :id="$post">...
{{-- Array [model, prefix]: generates dom_id($post, 'edit') e.g. "edit_post_1" --}} <x-turbo::frame :id="[$post, 'edit']">...
@endverbatim
By default, links and forms inside a frame target that same frame. When the server responds, Turbo extracts the matching <turbo-frame> from the response and swaps its content:
@verbatim
{{-- Submitting this form updates only this frame with the response --}}
<form action="{{ route('posts.update', $post) }}" method="POST">
@csrf
@method('PUT')
<input name="title" value="{{ $post->title }}">
<button type="submit">Save</button>
</form>
@endverbatim
Override the default frame target using data-turbo-frame:
@verbatim
{{-- Break out of the frame and navigate the entire page --}} View full page
@endverbatim
You can also set a default target on the frame itself:
@verbatim
@endverbatim
Frames can defer loading their content using the :src attribute. The frame fetches its content automatically:
@verbatim
Loading comments...
{{-- Viewport lazy load: fetches when the frame enters the viewport --}} <x-turbo::frame :id="$post" :src="route('posts.comments.index', $post)" loading="lazy">
Loading comments...
@endverbatim
Use data-turbo-action to make a frame navigation also update the browser URL and history:
<a href="/posts/1" data-turbo-frame="post_detail" data-turbo-action="advance">View</a>
This updates the frame content AND pushes the URL to the browser history, allowing Back button navigation.
Use request macros to detect if a request came from a Turbo Frame:
@verbatim
// Check if it came from a specific frame if ($request->wasFromTurboFrame(dom_id($post, 'create_comment'))) { // Return response for that specific frame }
@endverbatim
Add refresh="morph" to morph frame content instead of replacing it, preserving DOM state:
<turbo-frame id="post_1" refresh="morph">
<!-- Content will be morphed on refresh -->
</turbo-frame>
Customize how frame content is rendered using the turbo:before-frame-render event in JavaScript:
document.addEventListener("turbo:before-frame-render", (event) => {
// Access event.detail.newFrame to modify before rendering
});