hugo/docs/content/en/functions/go-template/return.md
Bjørn Erik Pedersen 5fd1e74903
Merge commit '9b0050e9aabe4be65c78ccf292a348f309d50ccd' as 'docs'
```
git subtree add --prefix=docs/ https://github.com/gohugoio/hugoDocs.git master --squash
```

Closes #11925
2024-01-27 10:48:57 +01:00

3.1 KiB

title description categories keywords action toc
return Used within partial templates, terminates template execution and returns the given value, if any.
aliases related returnType signatures
functions/partials/Include
functions/partials/IncludeCached
any
return [VALUE]
true

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.

{{% note %}} Unlike return statements in other languages, Hugo executes the first occurrence of the return statement regardless of its position within logical blocks. See usage notes below. {{% /note %}}

Example

By way of example, let's create a partial template that renders HTML, describing whether the given number is odd or even:

{{< code file="layouts/partials/odd-or-even.html" >}} {{ if math.ModBool . 2 }}

{{ . }} is even

{{ else }}

{{ . }} is odd

{{ end }} {{< /code >}}

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:

{{< code file="layouts/partials/is-even.html" >}} {{ return math.ModBool . 2 }} {{< /code >}}

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

{{% note %}} Unlike return statements in other languages, Hugo executes the first occurrence of the return statement regardless of its position within logical blocks {{% /note %}}

A partial that returns a value must contain only one return statement, placed at the end of the template.

For example:

{{< code file="layouts/partials/is-even.html" >}} {{ $result := false }} {{ if math.ModBool . 2 }} {{ $result = "even" }} {{ else }} {{ $result = "odd" }} {{ end }} {{ return $result }} {{< /code >}}

{{% note %}} The construct below is incorrect; it contains more than one return statement. {{% /note %}}

{{< code file="layouts/partials/do-not-do-this.html" >}} {{ if math.ModBool . 2 }} {{ return "even" }} {{ else }} {{ return "odd" }} {{ end }} {{< /code >}}