Views
- Introduction
- Creating and rendering views
- Passing data to views
- Rendering fragments
- Reloading and deploying views
- Views from packages
- Testing 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 -->23<html>4 <body>5 <h1>Hello, {{.}}</h1>6 </body>7</html>1<!-- resources/views/greeting.html -->23<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 greetings23import "go.laravel.com/web"45func Show(r *web.Request) *web.Response {6 return web.View("greeting", "James")7}1package greetings23import "go.laravel.com/web"45func 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.Slug2if !view.Exists(r, name) {3 name = "plans.default"4}56return web.View(name, plan)1name := "plans." + plan.Slug2if !view.Exists(r, name) {3 name = "plans.default"4}56return 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 reports23import (4 "go.laravel.com/storage"5 "go.laravel.com/view"6 "go.laravel.com/web"7)89type Summary struct {10 Month string11 Orders int12}1314func 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 }1920 if err := storage.From(r).Put(r, "reports/october.html", html); err != nil {21 return web.Fail(err)22 }2324 return web.Redirect("/reports")25}1package reports23import (4 "go.laravel.com/storage"5 "go.laravel.com/view"6 "go.laravel.com/web"7)89type Summary struct {10 Month string11 Orders int12}1314func 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 }1920 if err := storage.From(r).Put(r, "reports/october.html", html); err != nil {21 return web.Fail(err)22 }2324 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 users23import (4 "go.laravel.com/model"5 "go.laravel.com/web"67 "app/models"8)910type IndexPage struct {11 Title string12 Users []models.User13}1415func 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 }2021 return web.View("users.index", IndexPage{Title: "Users", Users: users})22}1package users23import (4 "go.laravel.com/model"5 "go.laravel.com/web"67 "app/models"8)910type IndexPage struct {11 Title string12 Users []models.User13}1415func 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 }2021 return web.View("users.index", IndexPage{Title: "Users", Users: users})22}
1<!-- resources/views/users/index.html -->23<h1>{{.Title}}</h1>45<ul>6 {{range .Users}}7 <li>{{.Name}}</li>8 {{end}}9</ul>1<!-- resources/views/users/index.html -->23<h1>{{.Title}}</h1>45<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 teams23import (4 "go.laravel.com/model"5 "go.laravel.com/view"6 "go.laravel.com/web"78 "app/models"9)1011func 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 }1617 team, err := model.Find[models.Team](r, id)18 if err != nil {19 return web.Fail(err)20 }2122 return next(view.Share(r, "team", team))23}1package teams23import (4 "go.laravel.com/model"5 "go.laravel.com/view"6 "go.laravel.com/web"78 "app/models"9)1011func 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 }1617 team, err := model.Find[models.Team](r, id)18 if err != nil {19 return web.Fail(err)20 }2122 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 posts23import (4 "html/template"56 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10)1112type ShowPage struct {13 Post models.Post14 Body template.HTML15}1617func 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 }2223 return web.View("posts.show", ShowPage{Post: post, Body: template.HTML(renderMarkdown(post.Body))})24}1package posts23import (4 "html/template"56 "go.laravel.com/model"7 "go.laravel.com/web"89 "app/models"10)1112type ShowPage struct {13 Post models.Post14 Body template.HTML15}1617func 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 }2223 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 -->23{{template "layout" .}}45{{define "content"}}{{template "form" .}}{{end}}67{{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 -->23{{template "layout" .}}45{{define "content"}}{{template "form" .}}{{end}}67{{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}56return res1res := web.View("posts.create", "")2if r.Header.Get("HX-Request") != "" {3 res = res.Fragment("form")4}56return 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 posts23import (4 "errors"5 "net/http"67 "go.laravel.com/validation"8 "go.laravel.com/validation/rule"9 "go.laravel.com/web"10)1112type StorePost struct {13 Title string `json:"title"`14}1516func (f *StorePost) Rules() validation.Rules {17 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))18}1920func 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 }2728 return web.View("posts.create", form.Title).29 Fragment("form").30 WithErrors(invalid).31 WithStatus(http.StatusUnprocessableEntity)32 }3334 // Store the post...3536 return web.Redirect("/posts")37}1package posts23import (4 "errors"5 "net/http"67 "go.laravel.com/validation"8 "go.laravel.com/validation/rule"9 "go.laravel.com/web"10)1112type StorePost struct {13 Title string `json:"title"`14}1516func (f *StorePost) Rules() validation.Rules {17 return validation.For(f, rule.Field(&f.Title, rule.Required, rule.Max(255)))18}1920func 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 }2728 return web.View("posts.create", form.Title).29 Fragment("form").30 WithErrors(invalid).31 WithStatus(http.StatusUnprocessableEntity)32 }3334 // Store the post...3536 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 views2var views embed.FS34func (q *Quotes) Register(app *laravel.Registrar) error {5 files, err := fs.Sub(views, "views")6 if err != nil {7 return err8 }9 app.Views("inspire", files)1011 return nil12}1//go:embed views2var views embed.FS34func (q *Quotes) Register(app *laravel.Registrar) error {5 files, err := fs.Sub(views, "views")6 if err != nil {7 return err8 }9 app.Views("inspire", files)1011 return nil12}
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 quote1laravel 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_test23import (4 "testing"56 "app/database/factories"7 "app/models"8 "app/tests"9)1011func TestTheUsersPageListsUsers(t *testing.T) {12 client := tests.New(t)13 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })1415 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_test23import (4 "testing"56 "app/database/factories"7 "app/models"8 "app/tests"9)1011func TestTheUsersPageListsUsers(t *testing.T) {12 client := tests.New(t)13 client.Create(factories.User, func(u *models.User) { u.Name = "Taylor" })1415 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 & 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")