return
Syntax
return [VALUE]
Returns
any
The return
statement is a custom addition to Go’s text/template package. Used within partial templates, the return
statement terminates template execution and returns the given value, if any.
The returned value may be of any data type including, but not limited to, bool
, float
, int
, map
, resource
, slice
, and string
.
A return
statement without a value returns an empty string of type template.HTML
.
Example
By way of example, let’s create a partial template that renders HTML, describing whether the given number is odd or even:
{{ if math.ModBool . 2 }}
<p>{{ . }} is even</p>
{{ else }}
<p>{{ . }} is odd</p>
{{ end }}
When called, the partial renders HTML:
{{ partial "odd-or-even.html" 42 }} → <p>42 is even</p>
Instead of rendering HTML, let’s create a partial that returns a boolean value, reporting whether the given number is even:
{{ return math.ModBool . 2 }}
With this template:
{{ $number := 42 }}
{{ if partial "is-even.html" $number }}
<p>{{ $number }} is even</p>
{{ else }}
<p>{{ $number }} is odd</p>
{{ end }}
Hugo renders:
<p>42 is even</p>
See additional examples in the partial templates section.
Usage
A partial that returns a value must contain only one return
statement, placed at the end of the template.
For example:
{{ $result := false }}
{{ if math.ModBool . 2 }}
{{ $result = "even" }}
{{ else }}
{{ $result = "odd" }}
{{ end }}
{{ return $result }}
{{ if math.ModBool . 2 }}
{{ return "even" }}
{{ else }}
{{ return "odd" }}
{{ end }}