Debian Codegraph @

docs/content/en/functions/go-template/with.md

raw
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 ```go-html-template
17 {{ $var := "foo" }}
18 {{ with $var }}
19 {{ . }} → foo
20 {{ end }}
21 ```
22
23 Use with the [`else`][] statement:
24
25 ```go-html-template
26 {{ $var := "foo" }}
27 {{ with $var }}
28 {{ . }} → foo
29 {{ else }}
30 {{ print "var is falsy" }}
31 {{ end }}
32 ```
33
34 Use `else with` to check multiple conditions:
35
36 ```go-html-template
37 {{ $v1 := 0 }}
38 {{ $v2 := 42 }}
39 {{ with $v1 }}
40 {{ . }}
41 {{ else with $v2 }}
42 {{ . }} → 42
43 {{ else }}
44 {{ print "v1 and v2 are falsy" }}
45 {{ end }}
46 ```
47
48 Initialize a variable, scoped to the current block:
49
50 ```go-html-template
51 {{ with $var := 42 }}
52 {{ . }} → 42
53 {{ $var }} → 42
54 {{ end }}
55 {{ $var }} → undefined
56 ```
57
58 ## Understanding context
59
60 See the [context][] section in the introduction to templating.
61
62 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.
63
64 With this contrived example:
65
66 ```go-html-template
67 {{ with 42 }}
68 {{ .Title }}
69 {{ end }}
70 ```
71
72 Hugo will throw an error:
73
74 can't evaluate field Title in type int
75
76 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.
77
78 > [!NOTE]
79 > Use the `$` to get the context passed into the template.
80
81 This template will render the page title as desired:
82
83 ```go-html-template
84 {{ with 42 }}
85 {{ $.Title }}
86 {{ end }}
87 ```
88
89 > [!NOTE]
90 > Gaining a thorough understanding of context is critical for anyone writing template code.
91
92 {{% include "/_common/functions/go-template/text-template.md" %}}
93
94 [`else`]: /functions/go-template/else/
95 [context]: /templates/introduction/#context