Skip to content

Views

Frontend

Views

Introduction

Returning entire HTML documents as strings from your route handlers isn't practical. Views separate your HTML into dedicated files under resources/views, leaving your handlers focused on loading the data a page needs.

Laravel's views are templates written in Jinja syntax, and every value they render is HTML-escaped automatically. For example, a simple greeting view in resources/views/greeting.html looks like this:

1<!-- resources/views/greeting.html -->
2 
3<html>
4 <body>
5 <h1>Hello, {{ name }}</h1>
6 </body>
7</html>
1<!-- resources/views/greeting.html -->
2 
3<html>
4 <body>
5 <h1>Hello, {{ name }}</h1>
6 </body>
7</html>

New Laravel applications build most of their UI with Inertia and React, which is the best fit for interactive web applications. Views are still useful whenever you want server-rendered HTML pages (including with tools like HTMX), as well as for Inertia's root view and HTML emails.

Looking for details on template syntax such as loops, layouts, filters, and components? Check out the templates guide.

Creating and rendering views

To create a view, place a file with the .html extension in resources/views, then return it from a handler with the view function:

1use laravel::prelude::*;
2use laravel::view::View;
3 
4pub async fn show() -> View {
5 view("greeting", data! { name => "James" })
6}
1use laravel::prelude::*;
2use laravel::view::View;
3 
4pub async fn show() -> View {
5 view("greeting", data! { name => "James" })
6}

The first argument is the view's name (its path inside resources/views without the .html extension), and the second argument is the data to pass to the template. For a view that needs no data, pass () as in view("about", ()).

If a view doesn't exist or references a variable that wasn't passed to it, Laravel responds with a 500 error. In debug mode, the error page points directly to the template's file and line.

For a static page that needs no handler logic or data of its own, register it directly with route.view("/about", "about").

Nested view directories

Views may be organized into subdirectories under resources/views. Use "dot" notation to reference nested views, so resources/views/admin/profile.html is rendered as admin.profile:

1view("admin.profile", data! { name => "Taylor" })
1view("admin.profile", data! { name => "Taylor" })

Templates reference other nested views using the same dot notation, such as {% extends "layouts.app" %}.

Determining if a view exists

To check whether a view exists before rendering it, call laravel::view::exists. It checks both your application's views and views registered by packages:

1if laravel::view::exists("admin.profile") {
2 // ...
3}
1if laravel::view::exists("admin.profile") {
2 // ...
3}

Rendering a view to a string

Sometimes you need a view's rendered HTML as a string rather than an HTTP response, such as when saving a generated report to file storage. Call render() to produce an Html value, then convert it to a String with into_string():

1use laravel::prelude::*;
2use laravel::storage;
3 
4pub async fn store() -> laravel::Result<Redirect> {
5 let html = view("reports.summary", data! { month => "October", orders => 42 }).render()?;
6 
7 storage::put("reports/october.html", html.into_string()).await?;
8 
9 Ok(Redirect::to("/reports"))
10}
1use laravel::prelude::*;
2use laravel::storage;
3 
4pub async fn store() -> laravel::Result<Redirect> {
5 let html = view("reports.summary", data! { month => "October", orders => 42 }).render()?;
6 
7 storage::put("reports/october.html", html.into_string()).await?;
8 
9 Ok(Redirect::to("/reports"))
10}

Passing data to views

Use the data! macro to pass variables to a view. List a local variable to pass it under its own name, or use name => value to give it a custom key. Each entry becomes a template variable, so the view below can loop over users and render {{ title }}:

1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::User;
5 
6pub async fn index() -> laravel::Result<View> {
7 let users = User::all().await?;
8 
9 Ok(view("users.index", data! { users, title => "Users" }))
10}
1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::User;
5 
6pub async fn index() -> laravel::Result<View> {
7 let users = User::all().await?;
8 
9 Ok(view("users.index", data! { users, title => "Users" }))
10}

You may also pass any struct that derives Serialize, and each struct field becomes a variable in the template. Defining a struct is especially helpful when multiple handlers render the same view, because the compiler verifies that every handler supplies all required fields:

1#[derive(Serialize)]
2struct UserList {
3 title: &'static str,
4 users: Vec<User>,
5}
6 
7pub async fn index() -> laravel::Result<View> {
8 let users = User::all().await?;
9 
10 Ok(view("users.index", UserList { title: "Users", users }))
11}
1#[derive(Serialize)]
2struct UserList {
3 title: &'static str,
4 users: Vec<User>,
5}
6 
7pub async fn index() -> laravel::Result<View> {
8 let users = User::all().await?;
9 
10 Ok(view("users.index", UserList { title: "Users", users }))
11}

Sharing data with all views

When every view in your application needs the same value, such as your support email address, share it globally inside with_views in src/app.rs:

1use laravel::foundation::ApplicationBuilder;
2use laravel::prelude::*;
3 
4pub fn configure() -> ApplicationBuilder {
5 Application::configure()
6 // ...
7 .with_views(|views, config| {
8 views.share("support_email", config.mail.from.email());
9 })
10}
1use laravel::foundation::ApplicationBuilder;
2use laravel::prelude::*;
3 
4pub fn configure() -> ApplicationBuilder {
5 Application::configure()
6 // ...
7 .with_views(|views, config| {
8 views.share("support_email", config.mail.from.email());
9 })
10}

A package may share data with all views by calling app.views().share(...) inside its service provider's register method.

For data that varies per request, such as the logged-in user, call laravel::view::share inside a middleware. Only views rendered during that request receive the shared value:

1use laravel::http::{Next, Request, Response, middleware};
2 
3use crate::models::User;
4 
5#[middleware]
6pub async fn share_user(request: Request, next: Next) -> laravel::Result<Response> {
7 let user: Option<User> = request.user().await?;
8 
9 laravel::view::share("user", user);
10 
11 Ok(next.run(request).await)
12}
1use laravel::http::{Next, Request, Response, middleware};
2 
3use crate::models::User;
4 
5#[middleware]
6pub async fn share_user(request: Request, next: Next) -> laravel::Result<Response> {
7 let user: Option<User> = request.user().await?;
8 
9 laravel::view::share("user", user);
10 
11 Ok(next.run(request).await)
12}

When the same variable name is defined in more than one place, Laravel uses the data passed directly to view(...) first, then data shared for the current request, and finally data shared globally with all views.

Passing markup

Because templates escape every value they output, raw HTML built in your handler would appear as literal text. When you want to render trusted HTML markup, such as a post body converted from Markdown with the markdown crate, wrap it in Html::raw and pass it with with_html:

1use laravel::prelude::*;
2use laravel::view::{Html, View};
3 
4use crate::models::Post;
5 
6pub async fn show(post: Post) -> View {
7 let body = Html::raw(markdown::to_html(&post.body));
8 
9 view("posts.show", data! { post }).with_html("body", body)
10}
1use laravel::prelude::*;
2use laravel::view::{Html, View};
3 
4use crate::models::Post;
5 
6pub async fn show(post: Post) -> View {
7 let body = Html::raw(markdown::to_html(&post.body));
8 
9 view("posts.show", data! { post }).with_html("body", body)
10}

markdown::to_html escapes any raw HTML inside the Markdown input, so this example is safe even for user-authored posts.

Never pass untrusted user input directly to Html::raw without escaping or sanitizing it first. Unescaped HTML is rendered as written and can allow cross-site scripting (XSS) attacks.

Rendering fragments

Sometimes a request only needs one section of a page, such as updating a search results list as the user types. Instead of duplicating markup in a second template, render a single named block from the existing view. For example, this view wraps its list in a results block:

1<!-- resources/views/users/index.html -->
2 
3{% extends "layouts.app" %}
4 
5{% block content %}
6 <form method="GET" action="/users">
7 <input type="search" name="q">
8 <button type="submit">Search</button>
9 </form>
10 
11 <ul id="results">
12 {% block results %}
13 {% for user in users %}
14 <li>{{ user.name }}</li>
15 {% endfor %}
16 {% endblock %}
17 </ul>
18{% endblock %}
1<!-- resources/views/users/index.html -->
2 
3{% extends "layouts.app" %}
4 
5{% block content %}
6 <form method="GET" action="/users">
7 <input type="search" name="q">
8 <button type="submit">Search</button>
9 </form>
10 
11 <ul id="results">
12 {% block results %}
13 {% for user in users %}
14 <li>{{ user.name }}</li>
15 {% endfor %}
16 {% endblock %}
17 </ul>
18{% endblock %}

Call fragment on the View to render only the results block:

1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::User;
5 
6#[laravel::query]
7pub struct Search {
8 #[default]
9 q: String,
10 fragment: Option<String>,
11}
12 
13pub async fn results(Query(search): Query<Search>) -> laravel::Result<View> {
14 let users = User::query().filter(User::name.contains(&search.q)).get().await?;
15 
16 Ok(view("users.index", data! { users }).fragment("results"))
17}
1use laravel::prelude::*;
2use laravel::view::View;
3 
4use crate::models::User;
5 
6#[laravel::query]
7pub struct Search {
8 #[default]
9 q: String,
10 fragment: Option<String>,
11}
12 
13pub async fn results(Query(search): Query<Search>) -> laravel::Result<View> {
14 let users = User::query().filter(User::name.contains(&search.q)).get().await?;
15 
16 Ok(view("users.index", data! { users }).fragment("results"))
17}

If a single handler serves both full page loads and partial updates, call fragment_if to render only the block when a condition is true:

1pub async fn index(Query(search): Query<Search>) -> laravel::Result<View> {
2 let users = User::query().filter(User::name.contains(&search.q)).get().await?;
3 
4 let partial = search.fragment.as_deref() == Some("results");
5 
6 Ok(view("users.index", data! { users }).fragment_if(partial, "results"))
7}
1pub async fn index(Query(search): Query<Search>) -> laravel::Result<View> {
2 let users = User::query().filter(User::name.contains(&search.q)).get().await?;
3 
4 let partial = search.fragment.as_deref() == Some("results");
5 
6 Ok(view("users.index", data! { users }).fragment_if(partial, "results"))
7}

Now /users?q=Alice renders the full page, while /users?q=Alice&fragment=results renders only the results block for your JavaScript to swap into #results.

Reloading and deploying views

In debug mode, Laravel reloads templates from disk on every render so your edits appear immediately when you refresh the browser. Outside debug mode, Laravel compiles each view the first time it is rendered and caches it until the application restarts.

Because your application reads views from resources/views at runtime rather than baking them into the binary, include resources/views alongside your compiled binary under your application's base path when deploying to your own servers. If you deploy to Laravel Cloud, this is handled for you automatically.

Views from packages

A package that provides pages or emails ships its own templates by embedding them in the binary with laravel::embed!, then registering them under a namespace via app.views() in its service provider:

1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4pub struct BillingServiceProvider;
5 
6impl ServiceProvider for BillingServiceProvider {
7 fn register(&self, app: &mut Registrar) {
8 app.views().namespace("billing", laravel::embed!("resources/views"));
9 }
10}
1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3 
4pub struct BillingServiceProvider;
5 
6impl ServiceProvider for BillingServiceProvider {
7 fn register(&self, app: &mut Registrar) {
8 app.views().namespace("billing", laravel::embed!("resources/views"));
9 }
10}

Package views are referenced with a namespace:: prefix, so billing::invoice resolves to the package's resources/views/invoice.html. To override a package's view in your application, place your customized template at resources/views/vendor/billing/invoice.html, which Laravel checks before falling back to the package's embedded copy.

namespace also accepts a directory path if you want to keep some of your application's own views outside resources/views, such as views.namespace("mail", "resources/mail") inside with_views.

Other template engines

Laravel renders .html templates with MiniJinja. To support another file extension such as .md, implement laravel::view::Engine and register it in a service provider:

1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3use laravel::view::{Engine, Html, Template};
4 
5pub struct Markdown;
6 
7impl Engine for Markdown {
8 fn render(&self, template: &Template<'_>) -> laravel::Result<Html> {
9 Ok(Html::raw(markdown::to_html(&template.source()?)))
10 }
11}
12 
13pub struct MarkdownServiceProvider;
14 
15impl ServiceProvider for MarkdownServiceProvider {
16 fn register(&self, app: &mut Registrar) {
17 app.views().engine("md", Markdown);
18 }
19}
1use laravel::container::Registrar;
2use laravel::foundation::ServiceProvider;
3use laravel::view::{Engine, Html, Template};
4 
5pub struct Markdown;
6 
7impl Engine for Markdown {
8 fn render(&self, template: &Template<'_>) -> laravel::Result<Html> {
9 Ok(Html::raw(markdown::to_html(&template.source()?)))
10 }
11}
12 
13pub struct MarkdownServiceProvider;
14 
15impl ServiceProvider for MarkdownServiceProvider {
16 fn register(&self, app: &mut Registrar) {
17 app.views().engine("md", Markdown);
18 }
19}

Any view with that extension is then rendered by your engine, so view("about", ()) renders resources/views/about.md.

Testing views

In your HTTP tests, you may assert which view a response rendered and inspect the data passed to it:

1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4use crate::models::User;
5 
6#[laravel::test]
7async fn the_users_page_lists_users(app: Application) -> laravel::Result<()> {
8 create!(User { name: "Taylor", email: "[email protected]", password: "password" }).await?;
9 
10 app.get("/users")
11 .await
12 .assert_view_is("users.index")
13 .assert_view_has("users.0.name", "Taylor")
14 .assert_view_where("users", |users: Vec<User>| users.len() == 1);
15 
16 Ok(())
17}
1use laravel::model::create;
2use laravel::testing::prelude::*;
3 
4use crate::models::User;
5 
6#[laravel::test]
7async fn the_users_page_lists_users(app: Application) -> laravel::Result<()> {
8 create!(User { name: "Taylor", email: "[email protected]", password: "password" }).await?;
9 
10 app.get("/users")
11 .await
12 .assert_view_is("users.index")
13 .assert_view_has("users.0.name", "Taylor")
14 .assert_view_where("users", |users: Vec<User>| users.len() == 1);
15 
16 Ok(())
17}

assert_view_has, assert_view_missing, assert_view_present, and assert_view_where support "dot" notation and inspect the data passed directly to view(...) (not data shared globally). To assert on the rendered HTML output itself, use assert_see.