return
Syntax
Returns
The return statement is a non-standard extension to Go’s text/template package. It terminates execution of the current template only; execution continues in any calling template. When used within a partial template, the return statement may also return a value to the caller.
New in v0.166.0
In earlier versions, the return statement was only supported within partial templates, limited to one return statement per template, executed regardless of its position within logical blocks. The return statement now follows normal flow control: you can use it in any template, in any position, any number of times, and Hugo executes it only when reached.
Return a value
Within a partial template, the return statement may return a value of any data type: bool, float, int, map, resource, slice, string, and others. When returning a value, any output rendered before the return statement is discarded.
Using the return statement with a value in any other template type produces an error.
For example, a partial template that returns a string value:
{{ if math.ModBool . 2 }}
{{ return "even" }}
{{ end }}
{{ return "odd" }}{{ partial "parity.html" 42 }} → evenA more practical example is a partial template that returns the cover image of the first page in a section that has one:
{{ range .Pages }}
{{ with .Resources.GetMatch "cover.*" }}
{{ return . }}
{{ end }}
{{ end }}{{ with partial "section-cover.html" . }}
<img src="{{ .RelPermalink }}" width="{{ .Width }}" height="{{ .Height }}" alt="">
{{ end }}Return early
Use the return statement without a value to stop execution of the current template:
<h2>{{ .Title }}</h2>
{{ if .Draft }}
<p>This article is a draft.</p>
{{ return }}
{{ end }}
{{ .Content }}Within a shortcode template, use a return statement after each validation check to avoid deeply nested conditional blocks:
{{ if not (.Get "src") }}
{{ errorf "The %q shortcode requires a src argument. See %s" .Name .Position }}
{{ return }}
{{ end }}
{{ if not (.Get "alt") }}
{{ errorf "The %q shortcode requires an alt argument. See %s" .Name .Position }}
{{ return }}
{{ end }}
<img src="{{ .Get "src" }}" alt="{{ .Get "alt" }}">Limitations
The return statement must be the last command in a pipeline. This produces an error:
{{ return "even" | strings.ToUpper }}