Keith misner h0 vxgz5ty xa unsplash

Hugo function to obtain OutputFormat of current page context

Hugo does not currently provide a function to obtain the current OutputFormat — this partial1 provides a simple solution.

Hugo allows adding custom output formats — yet, up to and including version 0.111.0, it does not offer a function to provide the OutputFormat of the current page context. As Hugo provides two functions to list available OutputFormats and those differ in whether they include the current OutputFormat, a simple call to complement provides the answer.


There is an open issue on GitHub regarding the lack of an OutputFormat property of the Page class. Joe Mooring came up with the same solution as below. But he also adds an important caveat: the below only works as long as all declared OutputFormats have the following declared in config.toml:

1notAlternative = false

You can add the below snippet to layouts/partials/_functions to use it in your templates.

 1{{- /* partial output-format
 2Returns the [OutputFormat](
 3of the page passed as argument in the current context.
 4USAGE: use as a function in the context of a page, as follows:
 5  {{- outputFormat := partial "partials/_functions/output-format" . }}
 6*/ -}}
 7{{- $outputFormat := false }}
 8{{- with (complement $.AlternativeOutputFormats $.OutputFormats) }}
 9  {{- $outputFormat = index . 0 }}
10{{- end }}
11{{- return $outputFormat }}
Save this as layouts/partials/_functions/output-format

In this post, we have seen how we can obtain the current OutputFormat with a simple partial in Hugo, even though Hugo itself does not yet offer a function for this purpose. It is important to note that this solution works under the condition that all declared OutputFormats have the parameter notAlternative = false declared in the config.toml file.

By adding the snippet mentioned above to layouts/partials/_functions, you can use the OutputFormat in your templates and dynamically adjust the output of the pages, depending on which format is currently being used.

Please remember that this is a temporary solution until Hugo possibly provides an integrated function for retrieving the current OutputFormat. It is best to subscribe to the open issue on GitHub to stay informed about future updates.

Photo by Keith Misner on Unsplash.

  1. A partial is a Hugo-specific template and is stored in the project directory under layouts/partials. Partials that do not output content but, like the present one, return a value, are often stored under layouts/partials/_functions. However, this is not a requirement. ↩︎