File: with.md

package info (click to toggle)
hugo 0.131.0-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 45,580 kB
  • sloc: javascript: 31,172; xml: 248; makefile: 73; sh: 42
file content (87 lines) | stat: -rw-r--r-- 1,943 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
---
title: with
description: Binds context (the dot) to the expression and executes the block if expression is truthy.
categories: []
keywords: []
action:
  aliases: []
  related:
    - functions/go-template/if
    - functions/go-template/else
    - functions/go-template/end
    - functions/collections/IsSet
  returnType:
  signatures: [with EXPR]
aliases: [/functions/with]
toc: true
---

{{% include "functions/go-template/_common/truthy-falsy.md" %}}

```go-html-template
{{ $var := "foo" }}
{{ with $var }}
  {{ . }} → foo
{{ end }}
```

Use with the [`else`] statement:

```go-html-template
{{ $var := "foo" }}
{{ with $var }}
  {{ . }} → foo
{{ else }}
  {{ print "var is falsy" }}
{{ end }}
```

Initialize a variable, scoped to the current block:

```go-html-template
{{ with $var := 42 }}
  {{ . }} → 42
  {{ $var }} → 42
{{ end }}
{{ $var }} → undefined
```

## Understanding context

At the top of a page template, the [context] (the dot) is a `Page` object. Inside of the `with` block, the context is bound to the value passed to the `with` statement.

With this contrived example:

```go-html-template
{{ with 42 }}
  {{ .Title }}
{{ end }}
```

Hugo will throw an error:

    can't evaluate field Title in type int

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.

{{% note %}}
Use the `$` to get the context passed into the template.
{{% /note %}}

This template will render the page title as desired:

```go-html-template
{{ with 42 }}
  {{ $.Title }}
{{ end }}
```

{{% note %}}
Gaining a thorough understanding of context is critical for anyone writing template code.
{{% /note %}}

[context]: /getting-started/glossary/#context

{{% include "functions/go-template/_common/text-template.md" %}}

[`else`]: /functions/go-template/else/