Hugo template functions
Hugo CodeThere are times using hugo that it is useful to be able to create a function in a template itself. I can already hear my past purist self yelling back at me that templates are not the place to put logic, but be calm old self. You will be ok.
The relatively simple trick I discovered is that you can create a partial template inline, and that it can return a value. For example, to have a simple function that returns true if a given year is a leap year you can use the following snippet:
{{- define "_partials/inline/isleap.html" }}
{{/* Takes a Year (int) and returns a true for a leap year or false for a common year */}}
{{ $d := time.AsTime (printf "%d-02-28" .)}}
{{ $d = $d.Add (time.ParseDuration "24h") }}
{{ return (eq $d.Month 2) }}
{{ end -}}
In this template or in another template, you can then use this function:
{{ if (partial "inline/isleap.html" 2024 )}}
{{/* The argument ----^^^^ */}}
{{/* (can also be a variable) */}}
<p>It's a leap year!</p>
{{ else }}
<p>It's not a leap year :(</p>
{{ end }}
The arguments are not terribly ergonomic, but if you find yourself needing a to break down a complex template into reusable places, it can be helpful.
See the hugo docs for the partial template documentation.