Return from partials

It seems that return does not work the way I would expect it to. For instance in JavaScript a return stops execution of whatever the script is running.

Apparently this does not work this way in Go templates?

{{ return }}
{{ $context := .context }}
{{- if eq "home" $context.Kind -}}
<script src="something"></script>
{{ end }}

(lazy sample, sorry, I wanted to just keep a partial in line but remove what it did for a bit). This will still print the script line.

So, is this a feature or a bug? I can twist my mind around a return being at any arbitrary position and then doing some more stuff, but I think that would be something that needs to be mentioned in the docs.

Also, assuming I return a value, will the returned value be the one at the position of the return or the value that it has at the end of the template (if I modify it further)?

1 Like

Interesting. I think this is a case of experimenting and documenting the results. Unless the Go docs for the template package has the answer:

Although I see no mention of return, so I wonder of @bep made the return function rather than it being a Go Template builtin.

Definitely going to watch your posts on this thread.

The Hugo templating return works differently.

  • A partial can have only 1 return statement.
  • So I think that it’s implied that it needs to be used only at the end of the partial.

I generally do this (pseudocode):

declare a var $var

update $var in various if conditions

{{ return $var }}

Docs: Partial Templates | Hugo

1 Like

Have you read the docs?

That is indeed what is expected. What @davidsneighbour has stumbled on is a case where actual behavior is not necessarily what one would expect if one does something other than intended — and it doesn’t throw an error when one does the ‘strange’ thing.

I have. Have you understood my irritation coming from different programming languages where the return partial is not enforced at the end of a routine but results in immediate return?

If “my” return in the first line is basically false, I wonder why it’s ignored instead of “bemoaned”.

Have you understood my irritation coming from me spending 10 hours of my vacation time to implement basic return support in partials, yet you expect me to spend 100 hours to get it in line with your expectations?

Let’s not take this further… For the new documentation I would wish that cursive would be more visible. It’s probably just a accessibility issue:


Is there a fast & easy way to add throwing an error if return is not at the end of the template (aside from comments), if present?

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.