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 with Go's html/template, which escapes every value for the place it appears, such as HTML text, an attribute, or a URL. 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, {{.}}</h1>
6 </body>
7</html>
1<!-- resources/views/greeting.html -->
2 
3<html>
4 <body>
5 <h1>Hello, {{.}}</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, and helpers? 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 web.View:

1package greetings
2 
3import "go.laravel.com/web"
4 
5func Show(r *web.Request) *web.Response {
6 return web.View("greeting", "James")
7}
1package greetings
2 
3import "go.laravel.com/web"
4 
5func Show(r *web.Request) *web.Response {
6 return web.View("greeting", "James")
7}

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 view, which the view reads as .. For a view that needs no data, pass nil, as in web.View("about", nil).

The view renders right after your handler returns. If the view doesn't exist, or reads a field that its data doesn't have, Laravel responds with a 500 error. In debug mode, the error page names the view and the line that failed.

For a static page that needs no handler logic or data of its own, register it directly in routes/web.go with route.View("/about", "about", nil).

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:

1return web.View("admin.profile", user)
1return web.View("admin.profile", user)

Views include other nested views using the same dot notation, such as {{template "admin.sidebar" .}}. Because dots stand for directories, keep them out of your file names.

Determining if a view exists

Sometimes a page has a view of its own for some records and a shared view for the rest, such as a pricing page with a custom layout for a few plans. To check whether a view exists before rendering it, call view.Exists with the request and the view's name. It checks both your application's views and views registered by packages:

1name := "plans." + plan.Slug
2if !view.Exists(r, name) {
3 name = "plans.default"
4}
5 
6return web.View(name, plan)
1name := "plans." + plan.Slug
2if !view.Exists(r, name) {
3 name = "plans.default"
4}
5 
6return web.View(name, plan)

Rendering a view to a string

Sometimes you need a view's rendered HTML rather than an HTTP response, such as when saving a generated report to file storage. Call view.Render with the request, the view's name, and its data, and it returns the HTML as bytes:

1package reports
2 
3import (
4 "go.laravel.com/storage"
5 "go.laravel.com/view"
6 "go.laravel.com/web"
7)
8 
9type Summary struct {
10 Month string
11 Orders int
12}
13 
14func Store(r *web.Request) *web.Response {
15 html, err := view.Render(r, "reports.summary", Summary{Month: "October", Orders: 42})
16 if err != nil {
17 return web.Fail(err)
18 }
19 
20 if err := storage.From(r).Put(r, "reports/october.html", html); err != nil {
21 return web.Fail(err)
22 }
23 
24 return web.Redirect("/reports")
25}
1package reports
2 
3import (
4 "go.laravel.com/storage"
5 "go.laravel.com/view"
6 "go.laravel.com/web"
7)
8 
9type Summary struct {
10 Month string
11 Orders int
12}
13 
14func Store(r *web.Request) *web.Response {
15 html, err := view.Render(r, "reports.summary", Summary{Month: "October", Orders: 42})
16 if err != nil {
17 return web.Fail(err)
18 }
19 
20 if err := storage.From(r).Put(r, "reports/october.html", html); err != nil {
21 return web.Fail(err)
22 }
23 
24 return web.Redirect("/reports")
25}

In a job or a command, pass the ctx it received instead of r. Without a request, the view may still build links with route and read config, but the helpers that read the request, such as csrfField, auth, and head, fail the render.

Your site's layout usually calls head, so a view that extends that layout fails to render from a job or a command. Give such a view a small layout of its own that calls none of the request's helpers.

Passing data to views

A view receives one value from your handler. Most pages show more than one thing, such as a title and a list of users, so pass a struct, and each of its fields becomes a value the view reads by name. For example, this handler loads the users and passes them to the view along with a title, so the view below can loop over .Users and render {{.Title}}:

1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10type IndexPage struct {
11 Title string
12 Users []models.User
13}
14 
15func Index(r *web.Request) *web.Response {
16 users, err := model.Query[models.User]().OrderBy("name").Get(r)
17 if err != nil {
18 return web.Fail(err)
19 }
20 
21 return web.View("users.index", IndexPage{Title: "Users", Users: users})
22}
1package users
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/web"
6 
7 "app/models"
8)
9 
10type IndexPage struct {
11 Title string
12 Users []models.User
13}
14 
15func Index(r *web.Request) *web.Response {
16 users, err := model.Query[models.User]().OrderBy("name").Get(r)
17 if err != nil {
18 return web.Fail(err)
19 }
20 
21 return web.View("users.index", IndexPage{Title: "Users", Users: users})
22}
1<!-- resources/views/users/index.html -->
2 
3<h1>{{.Title}}</h1>
4 
5<ul>
6 {{range .Users}}
7 <li>{{.Name}}</li>
8 {{end}}
9</ul>
1<!-- resources/views/users/index.html -->
2 
3<h1>{{.Title}}</h1>
4 
5<ul>
6 {{range .Users}}
7 <li>{{.Name}}</li>
8 {{end}}
9</ul>

A view can read only exported fields and methods, so name them with a capital letter. Defining a struct is especially helpful when multiple handlers render the same view, because the compiler checks that every handler supplies the right fields. You may also pass a map[string]any, but a misspelled key then renders nothing rather than failing.

Sharing data with all views

When every view in your application needs the same value, such as your support email address, read it from your configuration with the config helper rather than passing it from each handler:

1<a href="mailto:{{config.Mail.FromAddress}}">Contact support</a>
1<a href="mailto:{{config.Mail.FromAddress}}">Contact support</a>

For a value that your configuration doesn't hold, add a function that returns it to the ViewFuncs option in bootstrap/app.go. To learn how, check out the templates guide's section on functions of your own.

For data that varies per request, such as the team the user is working in, call view.Share inside a middleware. view.Share returns a copy of the request that carries the value, so pass that copy on to next. Only views rendered during that request receive the shared value:

1package teams
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/view"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func ShareCurrent(r *web.Request, next web.Next) *web.Response {
12 id, ok := r.Session().Value[int64]("team_id")
13 if !ok {
14 return next(r)
15 }
16 
17 team, err := model.Find[models.Team](r, id)
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 return next(view.Share(r, "team", team))
23}
1package teams
2 
3import (
4 "go.laravel.com/model"
5 "go.laravel.com/view"
6 "go.laravel.com/web"
7 
8 "app/models"
9)
10 
11func ShareCurrent(r *web.Request, next web.Next) *web.Response {
12 id, ok := r.Session().Value[int64]("team_id")
13 if !ok {
14 return next(r)
15 }
16 
17 team, err := model.Find[models.Team](r, id)
18 if err != nil {
19 return web.Fail(err)
20 }
21 
22 return next(view.Share(r, "team", team))
23}

Add ShareCurrent to the web middleware group in bootstrap/app.go with m.Web.Append(web.MiddlewareFunc(teams.ShareCurrent)). Every view the request renders, including your layout, may then read the team with shared, which returns nothing when the request didn't share that name:

1{{with shared "team"}}<span>{{.Name}}</span>{{end}}
1{{with shared "team"}}<span>{{.Name}}</span>{{end}}

When two middleware share a value under the same name, views receive the value from the middleware closer to the handler. You don't need to share the logged-in user, because {{user}} returns it in any view, or nothing for a guest.

Passing markup

Because views escape every string 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, pass it to the view as a template.HTML. Here, renderMarkdown is your own function that converts Markdown with the library you choose:

1package posts
2 
3import (
4 "html/template"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type ShowPage struct {
13 Post models.Post
14 Body template.HTML
15}
16 
17func Show(r *web.Request) *web.Response {
18 post, err := model.Find[models.Post](r, r.PathValue("post"))
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 return web.View("posts.show", ShowPage{Post: post, Body: template.HTML(renderMarkdown(post.Body))})
24}
1package posts
2 
3import (
4 "html/template"
5 
6 "go.laravel.com/model"
7 "go.laravel.com/web"
8 
9 "app/models"
10)
11 
12type ShowPage struct {
13 Post models.Post
14 Body template.HTML
15}
16 
17func Show(r *web.Request) *web.Response {
18 post, err := model.Find[models.Post](r, r.PathValue("post"))
19 if err != nil {
20 return web.Fail(err)
21 }
22 
23 return web.View("posts.show", ShowPage{Post: post, Body: template.HTML(renderMarkdown(post.Body))})
24}

The view then outputs {{.Body}} as markup.

Never convert untrusted user input to template.HTML 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 a form that htmx swaps in place after a submission. Instead of duplicating markup in a second view, render a single named block from the existing view. For example, this view defines its form as a form block:

1<!-- resources/views/posts/create.html -->
2 
3{{template "layout" .}}
4 
5{{define "content"}}{{template "form" .}}{{end}}
6 
7{{define "form"}}
8<form method="POST" action="/posts" hx-post="/posts" hx-swap="outerHTML">
9 {{csrfField}}
10 <input name="title" value="{{old "title" .}}">
11 {{with error "title"}}<p class="error">{{.}}</p>{{end}}
12</form>
13{{end}}
1<!-- resources/views/posts/create.html -->
2 
3{{template "layout" .}}
4 
5{{define "content"}}{{template "form" .}}{{end}}
6 
7{{define "form"}}
8<form method="POST" action="/posts" hx-post="/posts" hx-swap="outerHTML">
9 {{csrfField}}
10 <input name="title" value="{{old "title" .}}">
11 {{with error "title"}}<p class="error">{{.}}</p>{{end}}
12</form>
13{{end}}

Call Fragment on the response to render only the form block, without the layout or the rest of the page:

1return web.View("posts.create", "").Fragment("form")
1return web.View("posts.create", "").Fragment("form")

If a single handler serves both full page loads and partial updates, call Fragment only when the request asks for a piece of the page. htmx sends an HX-Request header with each of its requests:

1res := web.View("posts.create", "")
2if r.Header.Get("HX-Request") != "" {
3 res = res.Fragment("form")
4}
5 
6return res
1res := web.View("posts.create", "")
2if r.Header.Get("HX-Request") != "" {
3 res = res.Fragment("form")
4}
5 
6return res

Now a normal visit to /posts/create renders the full page, while htmx receives only the form block.

When a form that htmx swaps in place fails validation, send the form back with its errors instead of redirecting. Catch the validation error with errors.AsType, and pass it to the view with WithErrors, so the view's error and errors helpers show it:

1package posts
2 
3import (
4 "errors"
5 "net/http"
6 
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10)
11 
12type StorePost struct {
13 Title string `json:"title"`
14}
15 
16func (f *StorePost) Rules() validation.Rules {
17 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))
18}
19 
20func Store(r *web.Request) *web.Response {
21 form, err := r.Validate[StorePost]()
22 if err != nil {
23 invalid, ok := errors.AsType[*web.InputError](err)
24 if !ok {
25 return web.Fail(err)
26 }
27 
28 return web.View("posts.create", form.Title).
29 Fragment("form").
30 WithErrors(invalid).
31 WithStatus(http.StatusUnprocessableEntity)
32 }
33 
34 // Store the post...
35 
36 return web.Redirect("/posts")
37}
1package posts
2 
3import (
4 "errors"
5 "net/http"
6 
7 "go.laravel.com/validation"
8 "go.laravel.com/validation/rule"
9 "go.laravel.com/web"
10)
11 
12type StorePost struct {
13 Title string `json:"title"`
14}
15 
16func (f *StorePost) Rules() validation.Rules {
17 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))
18}
19 
20func Store(r *web.Request) *web.Response {
21 form, err := r.Validate[StorePost]()
22 if err != nil {
23 invalid, ok := errors.AsType[*web.InputError](err)
24 if !ok {
25 return web.Fail(err)
26 }
27 
28 return web.View("posts.create", form.Title).
29 Fragment("form").
30 WithErrors(invalid).
31 WithStatus(http.StatusUnprocessableEntity)
32 }
33 
34 // Store the post...
35 
36 return web.Redirect("/posts")
37}

Because the handler doesn't redirect, Laravel flashes no old input. Pass what the user typed to the view yourself, as this handler does with form.Title, and the view gives it to old as the default value. By default, htmx doesn't swap in a 422 response, so configure it to.

Reloading and deploying views

In debug mode, Laravel reads your views from resources/views on disk and reads them again when one changes, so your edits appear without restarting the application. While npm run dev runs, saving a view also reloads the page in your browser.

Outside debug mode, Laravel uses views compiled into your application's binary. New applications embed the resources/views directory in resources/resources.go and pass it to Laravel as the Views option in bootstrap/app.go, so your servers don't need a copy of resources/views. Laravel parses every view when the application starts, so a view with a syntax error stops the application with an error that names the file.

Views from packages

A package that provides pages or emails ships its own views by embedding them in its module, then registering them under a namespace with app.Views in its Register method:

1//go:embed views
2var views embed.FS
3 
4func (q *Quotes) Register(app *laravel.Registrar) error {
5 files, err := fs.Sub(views, "views")
6 if err != nil {
7 return err
8 }
9 app.Views("inspire", files)
10 
11 return nil
12}
1//go:embed views
2var views embed.FS
3 
4func (q *Quotes) Register(app *laravel.Registrar) error {
5 files, err := fs.Sub(views, "views")
6 if err != nil {
7 return err
8 }
9 app.Views("inspire", files)
10 
11 return nil
12}

Package views are referenced with a namespace:: prefix, so inspire::quote resolves to the package's views/quote.html. Laravel's own mail components live in the mail namespace.

To override a package's view in your application, place your customized view at resources/views/vendor/inspire/quote.html, which Laravel checks before falling back to the package's copy. To start from the package's copy, run vendor:publish with the namespace and the view's name, then edit the file it writes:

1laravel vendor:publish inspire quote
1laravel vendor:publish inspire quote

Testing views

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

1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/models"
8 "app/tests"
9)
10 
11func TestTheUsersPageListsUsers(t *testing.T) {
12 client := tests.New(t)
13 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
14 
15 client.Get("/users").
16 AssertOK().
17 AssertViewIs("users.index").
18 AssertViewHas("Users.0.Name", "Taylor").
19 AssertViewWhere("Users", func(users []models.User) bool { return len(users) == 1 })
20}
1package feature_test
2 
3import (
4 "testing"
5 
6 "app/database/factories"
7 "app/models"
8 "app/tests"
9)
10 
11func TestTheUsersPageListsUsers(t *testing.T) {
12 client := tests.New(t)
13 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })
14 
15 client.Get("/users").
16 AssertOK().
17 AssertViewIs("users.index").
18 AssertViewHas("Users.0.Name", "Taylor").
19 AssertViewWhere("Users", func(users []models.User) bool { return len(users) == 1 })
20}

AssertViewHas, AssertViewMissing, AssertViewPresent, and AssertViewWhere take a path of struct fields, map keys, and list indexes separated by dots, and inspect the data passed directly to web.View (not data shared by a middleware). To assert on the rendered HTML output itself, use AssertSee, which matches text whether or not the view escaped it, so AssertSee("Tom & Jerry") matches Tom &amp; Jerry.

To check the whole page at once, pass AssertRenders the view's name and the data you expect. Laravel renders that view with the response's request and session and compares the HTML, showing where the two differ:

1client.Get("/greeting").AssertOK().AssertRenders("greeting", "James")
1client.Get("/greeting").AssertOK().AssertRenders("greeting", "James")