Essentials / Turbo Frames

Docs Essentials

Turbo Frames

The Turbo Frame tag that ships with Turbo can be used in your templates just like any other HTML tag:

jinja
<turbo-frame id="{{ dom_id(post, 'create_comment') }}">
    <p>Loading...</p>
</turbo-frame>

In this case, the dom_id function creates a DOM ID that looks like create_comment_post_123. Turbo Laravel also ships with a frame macro that does this for you:

jinja
{% from "turbo::components" import frame %}

{% call frame(post, "create_comment") %}
    <p>Loading...</p>
{% endcall %}

You may also pass a string if you want to use your own DOM ID. Other attributes go in attrs, so if you want to turn a Turbo Frame into a lazy-loading Turbo Frame, you can do it like so:

jinja
{% call frame(post, "create_comment", attrs={"src": route("comments::create", post), "loading": "lazy"}) %}
    <p>Loading...</p>
{% endcall %}

The page at src renders a frame with the same ID, and Turbo swaps it in:

jinja
{# resources/views/comments/create.html #}
{% extends "layouts.app" %}

{% block content %}
    {% call frame(post, "create_comment") %}
        <form action="{{ route("comments::store", post) }}" method="post">
            {{ csrf_field() }}
            <textarea name="body">{{ old("body") }}</textarea>
            {% if error("body") %}<p>{{ error("body") }}</p>{% endif %}
            <button>Comment</button>
        </form>
    {% endcall %}
{% endblock %}

Since the page is a regular page, it also works on its own, such as when the user opens it in a new tab.

Detecting Turbo Frame Requests

You may want to detect in the backend whether a request came from a Turbo Frame. Turbo sends the frame's ID in the Turbo-Frame header, which the RequestExt trait reads:

rust
use laravel::http::Request;
use turbo::RequestExt;

if let Some(frame) = request.turbo_frame() {
    // ...
}

You may also check if the request came from a specific Turbo Frame:

rust
use laravel::http::Request;
use turbo::{DomId, RequestExt};

if request.was_from_turbo_frame(&post.dom_id_with("create_comment")) {
    // ...
}

A handler may use it to render only the frame's block, with laravel's view fragments, instead of the whole page:

rust
use laravel::prelude::*;
use laravel::view::View;
use turbo::RequestExt;

pub async fn create(request: Request, post: Post) -> View {
    view("comments.create", data! { post })
        .fragment_if(request.turbo_frame().is_some(), "content")
}

Failed Validations Inside Frames

When a form inside a Turbo Frame fails validation, laravel redirects back to the page the request came from. With frames, that's usually the page around the frame, which doesn't render the form. Turbo Laravel redirects to the form's page instead. Read more in Validation Response.