Templates
- Introduction
- Displaying data
- Expressions
- Control structures
- Layouts
- Components
- Laravel's helpers
- Formatting values
- Whitespace control
- Debugging templates
Introduction
Most pages need more than fixed HTML. For example, an orders page lists the logged-in user's orders, a sign-up form shows the errors from its last submission, and every page shares the same header and footer. Laravel's views are written with Go's html/template package, which gives you conditions, loops, layouts, and components, and escapes every value for the place it appears. Laravel adds functions for the work most pages share, such as linking to routes, protecting forms, and loading assets.
To learn where view files live and how handlers pass data to them, check out the views guide. For the full template language reference, check out the documentation of the text/template package, whose syntax html/template shares.
Displaying data
To display data passed to a view, wrap it in double curly braces. A view receives one value from its handler, which the view calls ., and .Title reads that value's Title field. For example, if a handler returns web.View("posts.show", post), your template may display the post like this:
1<!-- resources/views/posts/show.html -->23<article>4 <h1>{{.Title}}</h1>5 <p>{{.Votes}} votes</p>6</article>1<!-- resources/views/posts/show.html -->23<article>4 <h1>{{.Title}}</h1>5 <p>{{.Votes}} votes</p>6</article>
Any expression works inside the braces, including a value passed to a formatting function:
1Hello, {{.User.Name | upper}}. You have {{len .Orders}} orders.1Hello, {{.User.Name | upper}}. You have {{len .Orders}} orders.
You may also display values inside HTML attributes, such as an image's URL or its alt text. Quote the attribute's value as you would in plain HTML:
1<img src="{{.User.AvatarURL}}" alt="{{.User.Name}}">1<img src="{{.User.AvatarURL}}" alt="{{.User.Name}}">
Every view may also read your application's name, URL, and other settings with config, as in {{config.App.Name}}.
Escaping
Every value is escaped for the place it appears, so user input that contains a <script> tag shows as text and never runs. A javascript: link that a user typed renders as #ZgotmplZ, which goes nowhere, and a value in a style attribute can't add a background image of the user's choosing. Booleans display as true or false, as in aria-expanded="{{.Open}}".
A slice displays in Go's own format, such as [go web]. To show a list as readable text, join its items with join: {{.Tags | join ", "}}.
To display HTML that you trust as it is, such as the output of your own Markdown renderer, pass it from your handler as a template.HTML. To learn more, check out the views guide's section on passing markup.
Missing data
A view fails to render when it reads a field that its data doesn't have, such as a misspelled {{.Titel}}. It also fails when it reads a field through a nil pointer, such as {{.User.Name}} on a page for a guest whose User is nil. To show something only when a value is there, use with. It skips its body when the value is empty or nil, and inside the body, . is the value:
1{{with .User}}2 Hello, {{.Name}}3{{else}}4 Hello, guest5{{end}}1{{with .User}}2 Hello, {{.Name}}3{{else}}4 Hello, guest5{{end}}
A map is more forgiving, and a key it doesn't have renders nothing. A nil pointer that you display on its own renders as <nil>, so give a nullable column a fallback with default:
1<p>{{.Bio | default "No bio yet."}}</p>1<p>{{.Bio | default "No bio yet."}}</p>
Passing data to scripts
Sometimes a script on the page needs your handler's data, such as the points of a chart. Inside a <script> element, a value is written as a JavaScript value, so a slice becomes an array and a string is quoted:
1<script>2 const points = {{.Points}};3</script>1<script>2 const points = {{.Points}};3</script>
For an attribute that holds JavaScript, such as Alpine's x-data, encode the value as JSON with json. Always quote the attribute:
1<div x-data="{{json .Chart}}"></div>1<div x-data="{{json .Chart}}"></div>
Don't use json inside a <script> element. The view already writes values there as JavaScript, so json's output would arrive as a quoted string rather than an object.
Literal braces
Some frontend libraries, such as Vue, also use {{ ... }} in markup. To write those braces into the page rather than have the view read them, output them as a string. A string in backticks keeps everything inside it as it is, so you may write longer markup in it without escaping each brace:
1<div id="app">{{`{{ message }} from {{ sender }}`}}</div>1<div id="app">{{`{{ message }} from {{ sender }}`}}</div>
Comments
html/template removes every HTML comment from a view, so <!-- ... --> never reaches the browser. When you want to leave a note for whoever edits the view next, write a template comment instead:
1{{/* The public page of a published post. */}}2<h1>{{.Title}}</h1>1{{/* The public page of a published post. */}}2<h1>{{.Title}}</h1>
If a mail view needs Outlook's conditional comments, write them with the mso function.
Expressions
Values, fields, and items
Strings use double quotes, or backticks for a raw string that keeps backslashes as they are. Numbers and the booleans true and false are written as in Go. Templates have no syntax for lists and maps, so build them with list and dict:
1{{"Hello"}} {{`C:\Reports`}} {{42}} {{3.14}} {{true}}23{{$zones := list "UTC" "America/Chicago"}}4{{$sizes := dict "small" 12 "large" 18}}1{{"Hello"}} {{`C:\Reports`}} {{42}} {{3.14}} {{true}}23{{$zones := list "UTC" "America/Chicago"}}4{{$sizes := dict "small" 12 "large" 18}}
Read a field, or a map's key, with a dot. When a key isn't a valid name, such as first-name, or when you want a list's item by its position, use index. Positions start at 0, and last returns a list's last item. slice takes part of a list, and len counts its items:
1{{.User.Name}}2{{.Settings.theme}}3{{index .Settings "first-name"}}4{{(index .Orders 0).Number}}5{{(last .Orders).Number}}6{{slice .Items 1 3 | join ", "}}7{{len .Orders}}1{{.User.Name}}2{{.Settings.theme}}3{{index .Settings "first-name"}}4{{(index .Orders 0).Number}}5{{(last .Orders).Number}}6{{slice .Items 1 3 | join ", "}}7{{len .Orders}}
A field may also be a method. A method without arguments reads like a field, and a method with arguments takes them after its name, separated by spaces, as in {{.CreatedAt.Format "January 2, 2006"}}. If a method returns a value and an error, the render fails when the error isn't nil.
Operators
Templates have no operators such as == or +. Comparisons and logic are functions, and like every function, they take their arguments after their name:
| Functions | Meaning |
|---|---|
eq ne lt le gt ge |
Comparison: eq .Status "paid". eq also takes several values, and passes when the first matches any of the others: eq .Status "paid" "refunded". |
and or not |
Boolean logic. and stops at the first empty value, so and .User .User.Verified is safe for a guest. |
print, printf |
Joins values into text: print "Order #" .ID, or formats them as fmt.Sprintf does: printf "%.2f" .Average. |
x | function |
A pipeline, which passes x as the function's last argument: .Name | upper. |
(...) |
Groups a call inside another call: len (index .Orders 0).Items. |
Comparing values of different types, such as the number 1 with the text "1", fails the render with "incompatible types for comparison". Templates have no arithmetic, so add up values with sum from the list functions, or work them out in your handler. For an inline choice between two values, write a short if, as in {{if .Active}}Active{{else}}Inactive{{end}}.
Control structures
If statements
Most pages show something different depending on their data, such as a message for a customer who hasn't ordered anything yet. Use if, else if, and else to choose what to render:
1{{if eq (len .Orders) 1}}2 <p>You have one order.</p>3{{else if .Orders}}4 <p>You have {{len .Orders}} orders.</p>5{{else}}6 <p>You haven't ordered anything yet.</p>7{{end}}1{{if eq (len .Orders) 1}}2 <p>You have one order.</p>3{{else if .Orders}}4 <p>You have {{len .Orders}} orders.</p>5{{else}}6 <p>You haven't ordered anything yet.</p>7{{end}}
Use not to negate a condition, as in {{if not .User.Verified}}.
To render something only in one environment, such as an analytics script in production, compare the application's environment from config:
1{{if eq config.App.Env "production"}}2 <script defer src="/js/analytics.js"></script>3{{end}}1{{if eq config.App.Env "production"}}2 <script defer src="/js/analytics.js"></script>3{{end}}
Checking values
A condition passes when its value isn't empty, so {{if .Orders}} checks whether there are any orders, and {{if .Coupon}} checks whether a *Coupon was set. These values count as empty:
| Value | Empty when it's |
|---|---|
| A boolean | false. |
| A number | 0. |
| A string | "". |
| A slice or map | Without items, or nil. |
| A pointer or interface | nil. |
A struct is never empty, not even a zero time.Time. To check whether a time is set, call its IsZero method, as in {{if not .ShippedAt.IsZero}}, or store a nullable column as a *time.Time, which is nil when the column is NULL.
Loops
To render a list, loop over a slice, a map, or a number with range. Inside the loop, . is the current item, and $ is still the view's data. You may name the item, as in $user, and add an else that renders when there's nothing to loop over:
1<ul>2 {{range $user := .Users}}3 <li>{{$user.Name}} of {{$.Team.Name}}</li>4 {{else}}5 <li>No users yet.</li>6 {{end}}7</ul>1<ul>2 {{range $user := .Users}}3 <li>{{$user.Name}} of {{$.Team.Name}}</li>4 {{else}}5 <li>No users yet.</li>6 {{end}}7</ul>
To loop over a map's keys and values together, name both. A map loops in the order of its keys, so the list comes out the same on every render:
1{{range $name, $score := .Scores}}2 {{$name}}: {{$score}}3{{end}}1{{range $name, $score := .Scores}}2 {{$name}}: {{$score}}3{{end}}
You may skip an item with {{continue}}, or stop the loop early with {{break}}:
1{{range .Users}}2 {{if not .Active}}{{continue}}{{end}}3 {{if gt .Rank 10}}{{break}}{{end}}45 <li>{{.Name}}</li>6{{end}}1{{range .Users}}2 {{if not .Active}}{{continue}}{{end}}3 {{if gt .Rank 10}}{{break}}{{end}}45 <li>{{.Name}}</li>6{{end}}
The loop index
When you name two variables for a slice, the first is the item's index, starting at 0. The index is empty only for the first item, so {{if $i}} writes a separator before every item except the first:
1{{range $i, $tag := .Tags}}{{if $i}}, {{end}}{{$tag}}{{end}}1{{range $i, $tag := .Tags}}{{if $i}}, {{end}}{{$tag}}{{end}}
To mark the first item, compare its index with 0, as in <li class="{{if eq $i 0}}first{{end}}">.
Setting variables
When you use a value more than once, such as an order total, assign it to a variable with :=:
1{{$total := sum "Total" .Orders}}2<p>Total: {{$total}}</p>1{{$total := sum "Total" .Orders}}2<p>Total: {{$total}}</p>
To change a variable later, assign it with =. A variable you change inside a loop keeps its new value on the next item and after the loop, so a loop may remember the previous item. For example, this list of orders, sorted by status, shows a heading each time the status changes:
1{{$status := ""}}2{{range .Orders}}3 {{if ne .Status $status}}4 <h2>{{title .Status}}</h2>5 {{$status = .Status}}6 {{end}}78 <p>#{{.Number}}</p>9{{end}}1{{$status := ""}}2{{range .Orders}}3 {{if ne .Status $status}}4 <h2>{{title .Status}}</h2>5 {{$status = .Status}}6 {{end}}78 <p>#{{.Number}}</p>9{{end}}
with sets . to one value for its body instead, and skips the body when that value is empty:
1{{with .Coupon}}<p>Coupon {{.Code}} applied.</p>{{end}}1{{with .Coupon}}<p>Coupon {{.Code}} applied.</p>{{end}}
For more than a little logic, write a function of your own, or work the value out in the handler and pass it in.
Layouts
Most pages in an application share the same outer structure, such as a header, a navigation bar, and a footer. Define that shared structure once in a layout, and mark each place a page fills with a block. The markup inside a block is its default content:
1<!-- resources/views/layout.html -->23<!DOCTYPE html>4<html lang="en">5 <head>6 <meta charset="utf-8">7 {{head}}8 {{vite "resources/css/app.css"}}9 </head>10 <body>11 {{block "sidebar" .}}12 <nav><a href="/users">Users</a></nav>13 {{end}}1415 <main>16 {{block "content" .}}{{end}}17 </main>18 </body>19</html>1<!-- resources/views/layout.html -->23<!DOCTYPE html>4<html lang="en">5 <head>6 <meta charset="utf-8">7 {{head}}8 {{vite "resources/css/app.css"}}9 </head>10 <body>11 {{block "sidebar" .}}12 <nav><a href="/users">Users</a></nav>13 {{end}}1415 <main>16 {{block "content" .}}{{end}}17 </main>18 </body>19</html>
Each page then renders the layout with template, and fills the blocks it needs with define:
1<!-- resources/views/users/index.html -->23{{template "layout" .}}45{{define "content"}}6<ul>7 {{range .Users}}8 <li>{{.Name}}</li>9 {{end}}10</ul>11{{end}}1<!-- resources/views/users/index.html -->23{{template "layout" .}}45{{define "content"}}6<ul>7 {{range .Users}}8 <li>{{.Name}}</li>9 {{end}}10</ul>11{{end}}
Any block a page doesn't define keeps the layout's default content, such as the sidebar above. Laravel parses each view together with the files it includes, so the content that users.index defines never shows up in another page. To replace the sidebar on one page, define that block too:
1{{define "sidebar"}}<p>Filter users by role.</p>{{end}}1{{define "sidebar"}}<p>Filter users by role.</p>{{end}}
A page's block replaces the layout's default content entirely. To keep the default navigation and add to it, move the navigation into a view of its own and include it from both the layout and the page.
head renders the page's <title> through your application's title template, as in Users · Laravel, along with the description and social tags that the page's head metadata sets. A page may also set its own title by passing one to head, as in {{head "Users"}}. head writes its tags where you call it, so a call inside the page's content block would put the tags in the <body>. To let pages set the title, wrap the layout's head call in a block of its own:
1{{block "head" .}}{{head}}{{end}}1{{block "head" .}}{{head}}{{end}}
Then a page defines the head block, and may build the title from its data:
1{{define "head"}}{{head (print "Orders for " .Customer.Name)}}{{end}}1{{define "head"}}{{head (print "Orders for " .Customer.Name)}}{{end}}
A layout may extend another layout. For example, resources/views/admin/layout.html might render layout and define content as the admin menu followed by {{block "admin" .}}{{end}}. Each admin page then renders admin.layout and fills the admin block. Any block may also be rendered on its own as a fragment, such as a form that htmx swaps in place.
Including views
Some markup repeats within a page, such as a card for each post in a list. To include one view in another, name the view with template, and pass it the data it needs:
1{{range .Posts}}2 {{template "posts.card" .}}3{{end}}1{{range .Posts}}2 {{template "posts.card" .}}3{{end}}
template passes one value. To pass several values, build a map with dict, which takes names and values in pairs:
1{{template "posts.card" (dict "Post" . "Compact" true)}}1{{template "posts.card" (dict "Post" . "Compact" true)}}
template takes the view's name as written in the view, not a value from your data. To choose a view at run time, such as a page of its own for some plans, choose the name in your handler. To learn how, check out the views guide's section on determining if a view exists.
Components
Most applications repeat small pieces of markup, such as buttons and cards, across many pages. Write each piece once as a view in resources/views/components, and include it wherever you need it. A component that wraps other markup, such as a card around its content, takes that markup as one of its values:
1<!-- resources/views/components/card.html -->23<section class="card">4 <h2>{{.Title}}</h2>5 {{.Content}}6</section>1<!-- resources/views/components/card.html -->23<section class="card">4 <h2>{{.Title}}</h2>5 {{.Content}}6</section>
A view can't write the card's content inside the template call. Instead, the page writes each card's content as a block of its own, and render turns the block into HTML for the card to show. The block reads the data that you pass to render, which is the page's own data in this example:
1{{template "components.card" (dict "Title" "Orders" "Content" (render "orders" .))}}2{{template "components.card" (dict "Title" "Invoices" "Content" (render "invoices" .))}}34{{define "orders"}}<p>{{len .Orders}} this week</p>{{end}}5{{define "invoices"}}<p>{{len .Invoices}} unpaid</p>{{end}}1{{template "components.card" (dict "Title" "Orders" "Content" (render "orders" .))}}2{{template "components.card" (dict "Title" "Invoices" "Content" (render "invoices" .))}}34{{define "orders"}}<p>{{len .Orders}} this week</p>{{end}}5{{define "invoices"}}<p>{{len .Invoices}} unpaid</p>{{end}}
render escapes the block's values as it renders the block, so the card displays the HTML that render returns without escaping it again.
Component attributes
Reusable components often need to accept extra HTML attributes, such as a class or a data- attribute. Take the attributes as a map, and write them on the component's element with merge, which adds the component's defaults. A class or style that the page passes adds to the default, and any other attribute the page passes replaces the default:
1<!-- resources/views/components/button.html -->23<button {{merge .Attrs (dict "type" "button" "class" "btn")}}>{{.Label}}</button>1<!-- resources/views/components/button.html -->23<button {{merge .Attrs (dict "type" "button" "class" "btn")}}>{{.Label}}</button>
1{{template "components.button" (dict2 "Label" "Ship order"3 "Attrs" (dict "type" "submit" "class" "mr-2" "data-order" .ID "disabled" (not .CanShip))4)}}1{{template "components.button" (dict2 "Label" "Ship order"3 "Attrs" (dict "type" "submit" "class" "mr-2" "data-order" .ID "disabled" (not .CanShip))4)}}
1<button class="btn mr-2" data-order="42" disabled type="submit">Ship order</button>1<button class="btn mr-2" data-order="42" disabled type="submit">Ship order</button>
merge escapes each attribute's value, as {{...}} does. A value of true writes the bare name, as in disabled, and false leaves the attribute out.
Laravel's helpers
Laravel gives every view functions for the work most pages share, such as loading assets, generating URLs, rendering head metadata, protecting forms, and reading session data. Each helper reads what it needs, such as the current request, from the render, so you don't pass the request along yourself.
Every helper works in views that web.View renders, and in views that view.Render renders with a request. A mail view, or a view that a job or a command renders, has no request. There, the helpers that read the request fail the render: csrfField, csrfToken, old, selected, checked, error, errors, session, auth, guest, can, cannot, and head. The other helpers still work: user returns nothing, feature works for application-wide flags or when you pass a scope, route and url build URLs that start with APP_URL, and vite, viteAsset, and vendorAsset need only the application.
Assets with Vite
Your layout loads its scripts and styles through Vite. vite writes the <script> and <link> tags for your entry points, pointing to Vite's development server while it runs and to your production build otherwise. For React entry points, call viteReactRefresh before vite. viteAsset returns the URL of an image or font that Vite versioned:
1<head>2 {{viteReactRefresh}}3 {{vite "resources/css/app.css" "resources/js/app.tsx"}}4</head>5<img src="{{viteAsset "resources/images/logo.png"}}" alt="Acme">1<head>2 {{viteReactRefresh}}3 {{vite "resources/css/app.css" "resources/js/app.tsx"}}4</head>5<img src="{{viteAsset "resources/images/logo.png"}}" alt="Acme">
To learn how to run Vite, list your entry points, and give a script of your own the request's cspNonce, check out the asset bundling guide.
URLs
Writing URLs by hand means editing every view when a route's path changes. Instead, build the URL to a named route with route, which uses the host that the request arrived at. Give the route's parameters as names and values in pairs. A parameter that isn't in the route's path goes in the query string:
1<a href="{{route "posts.show" "post" .ID}}">{{.Title}}</a>2<a href="{{route "posts.index" "page" 2}}">Next page</a>1<a href="{{route "posts.show" "post" .ID}}">{{.Title}}</a>2<a href="{{route "posts.index" "page" 2}}">Next page</a>
If the route doesn't exist or a parameter is missing, the render fails, so a broken link shows up as an error in your tests rather than as a dead link on your site. To learn how to write those tests, check out the views guide's section on testing views.
For a path that has no route name, such as a page that route.View registers, url builds the full URL, as in {{url "/about"}}. To link to an asset shipped by a package, call vendorAsset, as in {{vendorAsset "inspire" "inspire.css"}}. To render a paginator's page links, include Laravel's pagination::links view, as in {{template "pagination::links" .Posts}}. To learn more, check out the pagination guide's section on rendering links in views.
Head metadata
The head function renders the page's title, description, and social tags from its head metadata. Call it inside your layout's <head> element:
1<head>2 <meta charset="utf-8">3 {{head}}4</head>1<head>2 <meta charset="utf-8">3 {{head}}4</head>
Handlers customize a page's metadata with head.Merge before returning the view, as in head.Merge(r, head.Head{Title: "Users"}). To let a page set its title from inside a layout, check out the section on layouts.
Forms and CSRF
Each form that posts to your application must include the CSRF token, and csrfField writes the hidden _token field that holds it. HTML forms can only send GET and POST, so a form that updates or deletes a record also adds methodField with the method the route expects:
1<form method="POST" action="{{route "posts.update" "post" .ID}}">2 {{csrfField}}3 {{methodField "PUT"}}45 <!-- ... -->6</form>1<form method="POST" action="{{route "posts.update" "post" .ID}}">2 {{csrfField}}3 {{methodField "PUT"}}45 <!-- ... -->6</form>
csrfToken returns the CSRF token itself, for JavaScript that sends it in an X-CSRF-TOKEN header. To learn more about sending the CSRF token from JavaScript, check out the CSRF protection guide's section on JavaScript and Inertia.
Validation errors and old input
After a form fails validation, Laravel redirects the user back to the form. error returns a field's first message, or "" when the field has none, and old returns what the user typed, so the page can show both:
1<label for="title">Title</label>2<input id="title" name="title" value="{{old "title"}}">34{{with error "title"}}<p class="error">{{.}}</p>{{end}}1<label for="title">Title</label>2<input id="title" name="title" value="{{old "title"}}">34{{with error "title"}}<p class="error">{{.}}</p>{{end}}
Name a nested field with dots, as in {{old "address.city"}}. old never returns password fields.
An edit form starts with the record's current values. Pass the current value to old as its default, whatever its type, and the field shows that value until the user submits the form. A number shows as text, and a nil pointer shows nothing. After a failed submission, the field shows what the user typed, and a field the user emptied stays empty:
1<input name="title" value="{{old "title" .Book.Title}}">2<input name="pages" value="{{old "pages" .Book.Pages}}">3<textarea name="notes">{{old "notes" .Book.Notes}}</textarea>1<input name="title" value="{{old "title" .Book.Title}}">2<input name="pages" value="{{old "pages" .Book.Pages}}">3<textarea name="notes">{{old "notes" .Book.Notes}}</textarea>
Select menus and checkboxes need a little more, because each option decides on its own whether it's chosen. For a select menu, selected reports whether an option is the field's choice, from what the user submitted or else from the current value. For checkboxes and radio buttons, checked reports whether the box is checked, from the same two sources. Values match when they display as the same text, so the number 3 matches the submitted text "3", and a list, such as a post's tags, matches any of its items:
1<select name="rating">2 {{range $rating := seq 5}}3 <option4 value="{{$rating}}"{{if selected "rating" $rating $.Book.Rating}} selected{{end}}5 >{{$rating}}</option>6 {{end}}7</select>89{{range .AllTags}}10 <input type="checkbox" name="tags[]" value="{{.}}"{{if checked "tags" . $.Post.Tags}} checked{{end}}>11{{end}}1<select name="rating">2 {{range $rating := seq 5}}3 <option4 value="{{$rating}}"{{if selected "rating" $rating $.Book.Rating}} selected{{end}}5 >{{$rating}}</option>6 {{end}}7</select>89{{range .AllTags}}10 <input type="checkbox" name="tags[]" value="{{.}}"{{if checked "tags" . $.Post.Tags}} checked{{end}}>11{{end}}
A single checkbox may take a bool as its current value, or false on a new form where the box starts unchecked. A browser sends nothing for a box that isn't checked, so put a hidden field with the same name before the box. After a failed submission, the box then stays unchecked if the user unchecked it:
1<input type="hidden" name="published" value="0">2<input3 type="checkbox"4 name="published"5 value="1"{{if checked "published" 1 .Post.Published}} checked{{end}}6>1<input type="hidden" name="published" value="0">2<input3 type="checkbox"4 name="published"5 value="1"{{if checked "published" 1 .Post.Published}} checked{{end}}6>
To list every message above the form, loop over errors. It lists the fields in the order your form's struct declares them, so the list reads top to bottom like the form:
1{{with errors}}2 <ul class="errors">3 {{range .}}{{range .Messages}}<li>{{.}}</li>{{end}}{{end}}4 </ul>5{{end}}1{{with errors}}2 <ul class="errors">3 {{range .}}{{range .Messages}}<li>{{.}}</li>{{end}}{{end}}4 </ul>5{{end}}
If a page has several forms whose errors go in named bags, pass the bag's name last, as in {{error "email" "login"}} and {{errors "login"}}. To learn how to show a form's errors without a redirect, such as for a form that htmx swaps in place, check out the views guide's section on rendering fragments.
Users and abilities
Most layouts show something different to a logged-in user, such as their name in place of a Log in link. auth reports whether a user is logged in, and guest reports whether the visitor is a guest. user returns the logged-in user, or nothing for a guest, so with shows the user's name only when there is a user:
1<nav>2 {{with user}}3 <span>{{.Name}}</span>4 {{else}}5 <a href="{{route "login"}}">Log in</a>6 {{end}}7</nav>1<nav>2 {{with user}}3 <span>{{.Name}}</span>4 {{else}}5 <a href="{{route "login"}}">Log in</a>6 {{end}}7</nav>
Some links make sense only to users who may follow them, such as Edit on a post that its author is reading. To show a link only to those users, pass an ability to can, and cannot does the opposite. A view can only call the functions you give it, so add your policies to ViewFuncs in bootstrap/app.go, as the section on functions of your own shows. A view's values aren't pointers, so take the post as a value and pass its address to the policy:
1"updatePost": func(post models.Post) auth.Ability[models.User] { return policies.UpdatePost(&post) },1"updatePost": func(post models.Post) auth.Ability[models.User] { return policies.UpdatePost(&post) },
1{{range .Posts}}2 <article>3 <h2>{{.Title}}</h2>4 {{if can (updatePost .)}}<a href="{{route "posts.edit" "post" .ID}}">Edit</a>{{end}}5 </article>6{{end}}1{{range .Posts}}2 <article>3 <h2>{{.Title}}</h2>4 {{if can (updatePost .)}}<a href="{{route "posts.edit" "post" .ID}}">Edit</a>{{end}}5 </article>6{{end}}
can checks the ability as auth.Can does in a handler, so your handler doesn't need to work out which posts the user may edit.
Hiding a link doesn't protect the action behind it. The handler for the action must still call auth.Authorize.
Feature flags
To show or hide part of a page behind a feature flag, call feature with the flag's stored name. It checks the flag for the logged-in user (or globally for an application-wide flag), returning its type's zero value (such as false or "") when inactive or the flag's value when active. For a flag scoped to another model, such as a team, pass the scope as the second argument:
1{{if feature "new_api"}}2 <a href="/api/docs">Try the new API</a>3{{end}}45{{if feature "billing_v2" .Team}}6 <a href="/billing">Manage billing</a>7{{end}}1{{if feature "new_api"}}2 <a href="/api/docs">Try the new API</a>3{{end}}45{{if feature "billing_v2" .Team}}6 <a href="/billing">Manage billing</a>7{{end}}
Session data
After a form saves, you'll often show a status message that the redirect flashed to the session. session reads a value from the session, and returns nothing when the session has no such value, so with skips its body:
1{{with session "status"}}<div class="alert">{{.}}</div>{{end}}1{{with session "status"}}<div class="alert">{{.}}</div>{{end}}
shared reads a value that a middleware shared with every view, such as the team the user works in, as in {{with shared "team"}}{{.Name}}{{end}}. To learn how to share one, check out the views guide's section on sharing data with all views.
csrfField, csrfToken, old, selected, checked, error, and session need a session. On routes outside the web middleware group, they render or return nothing.
Formatting values
Values often need formatting before they reach the page, such as a date in your customer's format or a name in title case. Laravel gives every view the formatting functions most pages need. A function that takes options takes the value last, so you may also pass the value through a pipeline with |, and chain pipelines from left to right:
1<tr>2 <td>{{title .CustomerName}}</td>3 <td>{{.Status | upper}}</td>4 <td>{{date "Jan 2, 15:04" .PlacedAt}}</td>5 <td>{{forHumans .CreatedAt}}</td>6 <td>{{.Notes | default "No notes"}}</td>7 <td>{{pluck "Email" .Users | join ", "}}</td>8</tr>1<tr>2 <td>{{title .CustomerName}}</td>3 <td>{{.Status | upper}}</td>4 <td>{{date "Jan 2, 15:04" .PlacedAt}}</td>5 <td>{{forHumans .CreatedAt}}</td>6 <td>{{.Notes | default "No notes"}}</td>7 <td>{{pluck "Email" .Users | join ", "}}</td>8</tr>
| Function | Result |
|---|---|
upper, lower |
The value's text in upper or lower case. |
title |
Each word capitalized: {{title "a nice title"}} is A Nice Title. |
date |
A time.Time in a layout, January 2, 2006 unless you give another: {{date "Jan 2, 15:04" .PlacedAt}}. Give a location after the layout to show it there: {{date "Jan 2, 15:04" "America/Chicago" .PlacedAt}}. Leave the location out for a date column, which holds a day rather than a moment. |
forHumans |
How long ago, or until, a time is: 3 minutes ago, or in 2 hours. |
compactForHumans |
How long ago, or until, a time is, with an abbreviated unit: {{compactForHumans .CreatedAt}} renders 3m ago instead of 3 minutes ago. |
now |
The current time on the application's clock, which time travel moves in tests: {{date "2006" now}}. |
default |
A fallback for an empty value, such as "", 0, nil, or a zero time.Time: {{.Bio | default "No bio yet."}}. |
round |
A number rounded to whole numbers, or to the decimals you give: {{round 2 .Average}}. A numeric.Decimal rounds exactly and keeps those decimals, so {{round 2 .Price}} of 19.5 is 19.50. |
date, forHumans, and compactForHumans also take a date.Date. Both relative formats show today for today's date. All three render nothing for a nil or zero time.Time or date.Date, so a nullable column or an empty create-form model doesn't need an if around it.
Working with lists
A page often needs a list in a different shape than your handler loaded it, such as orders grouped by their status. Laravel adds these list functions to every view:
| Function | Result |
|---|---|
list |
A list of the values you give, such as fixed options: {{range list "UTC" "America/Chicago"}}. |
join |
The items as text, joined by a separator: {{.Tags | join ", "}}. |
first, last |
The first or last item, or nothing for an empty list. |
sort |
The items in order, or ordered by a field: {{range sort "Name" .Users}}. |
reverse, unique |
The items in the opposite order, or without repeats. |
pluck |
A field of each item: {{pluck "Email" .Users | join ", "}}. |
groupBy |
The items in groups that share a field, each with its Key and its Items. |
batch |
The items in rows of a size, for a grid: {{range batch 3 .Products}}. |
sum, min, max |
The total, smallest, or largest of the numbers, or of a field: {{sum "Total" .Orders}}. |
seq |
The numbers from 1 to a last one, or from a first to a last: {{range seq 1 5}}. |
A field may name a nested field, such as Author.Name, or a key of a map. Money kept as numeric.Decimal works with each function, so sum adds amounts exactly, and sort, min, and max compare them as numbers. min and max of an empty list return nothing, so pair them with default or with.
For example, this orders page groups the orders by their status and shows each group's total:
1{{range groupBy "Status" .Orders}}2 <h2>{{title .Key}} ({{len .Items}})</h2>3 <p>Total: {{sum "Total" .Items | round 2}}</p>4 <ul>5 {{range .Items}}<li>#{{.Number}}</li>{{end}}6 </ul>7{{end}}1{{range groupBy "Status" .Orders}}2 <h2>{{title .Key}} ({{len .Items}})</h2>3 <p>Total: {{sum "Total" .Items | round 2}}</p>4 <ul>5 {{range .Items}}<li>#{{.Number}}</li>{{end}}6 </ul>7{{end}}
Functions of your own
When the built-in functions don't cover what you need, such as naming an order's status for your customers, add a function of your own to the ViewFuncs option in bootstrap/app.go. Each function is an ordinary Go function. ViewFuncs receives ctx, the context of each render, so a function that needs the request or the application reads it from ctx, as Laravel's helpers do:
1// bootstrap/app.go2ViewFuncs: func(ctx context.Context) template.FuncMap {3 return template.FuncMap{4 "statusLabel": orders.StatusLabel,5 "daysLeft": func(end time.Time) int {6 return int(end.Sub(date.Now(ctx)).Hours() / 24)7 },8 }9},1// bootstrap/app.go2ViewFuncs: func(ctx context.Context) template.FuncMap {3 return template.FuncMap{4 "statusLabel": orders.StatusLabel,5 "daysLeft": func(end time.Time) int {6 return int(end.Sub(date.Now(ctx)).Hours() / 24)7 },8 }9},
1<p>{{statusLabel .Status}}</p>2<p>{{daysLeft .Trial.EndsAt}} days left in your trial.</p>1<p>{{statusLabel .Status}}</p>2<p>{{daysLeft .Trial.EndsAt}} days left in your trial.</p>
daysLeft reads the time from the application's clock with date.Now(ctx), so time travel in a test moves it too.
The str, number, and date packages have more functions than every view gets, such as str.Limit for shortening a description and number.Cents for showing an amount of money. You may add any of them to ViewFuncs as well. A generic function needs its type in brackets, as in number.Cents[int64]:
1ViewFuncs: func(ctx context.Context) template.FuncMap {2 return template.FuncMap{3 "limit": str.Limit,4 "plural": str.Plural,5 "cents": number.Cents[int64],6 }7},1ViewFuncs: func(ctx context.Context) template.FuncMap {2 return template.FuncMap{3 "limit": str.Limit,4 "plural": str.Plural,5 "cents": number.Cents[int64],6 }7},
1<td>{{limit .Description 60}}</td>2<td>{{len .Items}} {{plural "item" (len .Items)}}</td>3<td>{{cents .TotalCents "USD"}}</td>1<td>{{limit .Description 60}}</td>2<td>{{len .Items}} {{plural "item" (len .Items)}}</td>3<td>{{cents .TotalCents "USD"}}</td>
To find the other functions you may add, such as str.Excerpt, number.FileSize, and date.ForHumans, check out the strings and numbers guide and the dates and time guide.
A view passes each value to a function as it is, without converting it. So a function that takes a string fails on a named string type, such as type Status string, and the render stops with the error "wrong type for value; expected string". To accept such values, take any and format the value with fmt.Sprint, or take your own type:
1"headline": func(value any) string { return str.Headline(fmt.Sprint(value)) },1"headline": func(value any) string { return str.Headline(fmt.Sprint(value)) },
If your function has the same name as one of Laravel's helpers, your views use your function instead. A package may add functions for every view with app.ViewFuncs. To learn more, check out the package guide's section on what a package can add.
Whitespace control
Adding - inside a tag's braces removes the whitespace, including newlines, on that side of the tag. Put a space between the - and the rest of the tag, because {{-3}} is the number -3:
1<ul>2 {{- range .Items}}3 <li>{{.}}</li>4 {{- end}}5</ul>1<ul>2 {{- range .Items}}3 <li>{{.}}</li>4 {{- end}}5</ul>
Debugging templates
Laravel parses every view when the application starts. A view that doesn't parse, or that calls a function no one defined, stops the application with an error that names the file.
A misspelled field or view name, such as {{.Titel}}, parses fine and fails only when that line renders. The request then gets a 500 response, and the error names the view and the line. A mistake in a branch that rarely runs, such as inside {{if .Refunded}}, can wait a long time to show up. To catch it early, give each view a test that renders each of its branches.
When a view doesn't show what you expect, look at the data it has. dump renders a value in Go syntax inside a <pre> element, and puts each field on a line of its own. For a pointer, dump shows the value it points to, so a nullable column reads &"Pays by ACH", and {{dump user}} shows the logged-in user's fields:
1{{dump .Invoice.LineItems}}1{{dump .Invoice.LineItems}}
1[]models.LineItem{2 models.LineItem{3 ID: 8,4 Description: "Design sprint",5 Notes: &"Workshop with the founders",6 Quantity: numeric.MustParse("1.50"),7 },8}1[]models.LineItem{2 models.LineItem{3 ID: 8,4 Description: "Design sprint",5 Notes: &"Workshop with the founders",6 Quantity: numeric.MustParse("1.50"),7 },8}
dump renders only in debug mode, so a dump call that you forget in a view never shows in production.