| 1 |
--- |
| 2 |
title: with |
| 3 |
description: Binds context (the dot) to the expression and executes the block if expression is truthy. |
| 4 |
categories: [] |
| 5 |
keywords: [] |
| 6 |
params: |
| 7 |
functions_and_methods: |
| 8 |
aliases: [] |
| 9 |
returnType: |
| 10 |
signatures: [with EXPR] |
| 11 |
aliases: [/functions/with] |
| 12 |
--- |
| 13 |
|
| 14 |
{{% include "/_common/functions/truthy-falsy.md" %}} |
| 15 |
|
| 16 |
## Usage |
| 17 |
|
| 18 |
```go-html-template |
| 19 |
{{ $var := "foo" }} |
| 20 |
{{ with $var }} |
| 21 |
{{ . }} → foo |
| 22 |
{{ end }} |
| 23 |
``` |
| 24 |
|
| 25 |
Use with the [`else`][] statement: |
| 26 |
|
| 27 |
```go-html-template |
| 28 |
{{ $var := "foo" }} |
| 29 |
{{ with $var }} |
| 30 |
{{ . }} → foo |
| 31 |
{{ else }} |
| 32 |
{{ print "var is falsy" }} |
| 33 |
{{ end }} |
| 34 |
``` |
| 35 |
|
| 36 |
Use `else with` to check multiple conditions: |
| 37 |
|
| 38 |
```go-html-template |
| 39 |
{{ $v1 := 0 }} |
| 40 |
{{ $v2 := 42 }} |
| 41 |
{{ with $v1 }} |
| 42 |
{{ . }} |
| 43 |
{{ else with $v2 }} |
| 44 |
{{ . }} → 42 |
| 45 |
{{ else }} |
| 46 |
{{ print "v1 and v2 are falsy" }} |
| 47 |
{{ end }} |
| 48 |
``` |
| 49 |
|
| 50 |
Initialize a variable, scoped to the current block: |
| 51 |
|
| 52 |
```go-html-template |
| 53 |
{{ with $var := 42 }} |
| 54 |
{{ . }} → 42 |
| 55 |
{{ $var }} → 42 |
| 56 |
{{ end }} |
| 57 |
{{ $var }} → undefined |
| 58 |
``` |
| 59 |
|
| 60 |
## Understanding context |
| 61 |
|
| 62 |
See the [context][] section in the introduction to templating. |
| 63 |
|
| 64 |
For example, at the top of a _page_ template, the [context](g) (the dot) is a `Page` object. Inside of the `with` block, the context is bound to the value passed to the `with` statement. |
| 65 |
|
| 66 |
With this contrived example: |
| 67 |
|
| 68 |
```go-html-template |
| 69 |
{{ with 42 }} |
| 70 |
{{ .Title }} |
| 71 |
{{ end }} |
| 72 |
``` |
| 73 |
|
| 74 |
Hugo will throw an error: |
| 75 |
|
| 76 |
can't evaluate field Title in type int |
| 77 |
|
| 78 |
The error occurs because we are trying to use the `Title` method on an integer instead of a `Page` object. Inside of the `with` block, if we want to render the page title, we need to get the context passed into the template. |
| 79 |
|
| 80 |
> [!NOTE] |
| 81 |
> Use the `$` to get the context passed into the template. |
| 82 |
|
| 83 |
This template will render the page title as desired: |
| 84 |
|
| 85 |
```go-html-template |
| 86 |
{{ with 42 }} |
| 87 |
{{ $.Title }} |
| 88 |
{{ end }} |
| 89 |
``` |
| 90 |
|
| 91 |
> [!NOTE] |
| 92 |
> Gaining a thorough understanding of context is critical for anyone writing template code. |
| 93 |
|
| 94 |
{{% include "/_common/functions/go-template/text-template.md" %}} |
| 95 |
|
| 96 |
[`else`]: /functions/go-template/else/ |
| 97 |
[context]: /templates/introduction/#context |