Debian Codegraph @

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

raw
1 ---
2 title: return
3 description: Used within partial templates, terminates template execution and returns the given value, if any.
4 categories: []
5 keywords: []
6 params:
7 functions_and_methods:
8 aliases: []
9 returnType: any
10 signatures: ['return [VALUE]']
11 ---
12
13 The `return` statement is a non-standard extension to Go's [`text/template`][] package. Used within _partial_ templates, the `return` statement terminates template execution and returns the given value, if any.
14
15 The returned value may be of any data type including, but not limited to, [`bool`](g), [`float`](g), [`int`](g), [`map`](g), [`resource`](g), [`slice`](g), or [`string`](g).
16
17 A `return` statement without a value returns an empty string of type `template.HTML`.
18
19 > [!NOTE]
20 > Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks. See [usage](#usage) notes below.
21
22 ## Example
23
24 By way of example, let's create a _partial_ template that _renders_ HTML, describing whether the given number is odd or even:
25
26 ```go-html-template {file="layouts/_partials/odd-or-even.html"}
27 {{ if math.ModBool . 2 }}
28 <p>{{ . }} is even</p>
29 {{ else }}
30 <p>{{ . }} is odd</p>
31 {{ end }}
32 ```
33
34 When called, the _partial_ template renders HTML:
35
36 ```go-html-template
37 {{ partial "odd-or-even.html" 42 }} → <p>42 is even</p>
38 ```
39
40 Instead of rendering HTML, let's create a _partial_ template that _returns_ a boolean value, reporting whether the given number is even:
41
42 ```go-html-template {file="layouts/_partials/is-even.html"}
43 {{ return math.ModBool . 2 }}
44 ```
45
46 With this template:
47
48 ```go-html-template
49 {{ $number := 42 }}
50 {{ if partial "is-even.html" $number }}
51 <p>{{ $number }} is even</p>
52 {{ else }}
53 <p>{{ $number }} is odd</p>
54 {{ end }}
55 ```
56
57 Hugo renders:
58
59 ```html
60 <p>42 is even</p>
61 ```
62
63 ## Usage
64
65 > [!NOTE]
66 > Unlike `return` statements in other languages, Hugo executes the first occurrence of the `return` statement regardless of its position within logical blocks.
67
68 A _partial_ template that returns a value must contain only one `return` statement, placed at the end of the template.
69
70 For example:
71
72 ```go-html-template {file="layouts/_partials/is-even.html"}
73 {{ $result := false }}
74 {{ if math.ModBool . 2 }}
75 {{ $result = "even" }}
76 {{ else }}
77 {{ $result = "odd" }}
78 {{ end }}
79 {{ return $result }}
80 ```
81
82 > [!NOTE]
83 > The construct below is incorrect; it contains more than one `return` statement.
84
85 ```go-html-template {file="layouts/_partials/do-not-do-this.html"}
86 {{ if math.ModBool . 2 }}
87 {{ return "even" }}
88 {{ else }}
89 {{ return "odd" }}
90 {{ end }}
91 ```
92
93 [`text/template`]: https://pkg.go.dev/text/template