Skip to main content

return

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.

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.

Example​

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

When called, the partial renders HTML:

{{ partial "odd-or-even.html" 42 }} → 42 is even

Instead of rendering HTML, let's create a partial that returns a boolean value, reporting whether the given number is even:

With this template:

{{ $number := 42 }}
{{ if partial "is-even.html" $number }}
{{ $number }} is even
{{ else }}
{{ $number }} is odd
{{ end }}

Hugo renders:

42 is even

See additional examples in the partial templates section.

Usage​

Unlike return statements in other languages, Hugo executes the first occurrence of the return statement regardless of its position within logical blocks.

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

For example:

The construct below is incorrect; it contains more than one return statement.