Next level Hugo with blocks

What

Hugo blocks are beneficial to prevent unnecessary repetition in Hugo themes. It’s not the same thing as partials, which are, roughly speaking, the Hugo version of includes with an attractive cache option.

The most popular block in Hugo themes is the main block you can find in layouts/_default/baseof.html, which is the base template:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>{{ block "title" . }}{{ .Site.Title }}{{ end }}</title>
  </head>
  <body>
    {{ block "main" . }}{{ end }}
    {{ block "footer" . }}{{ end }}
  </body>
</html>

It allows for extending those blocks in other templates:

{{ define "main" }}
  <h1>Posts</h1>
  {{ range .Pages }}
    <article>
      <h2>{{ .Title }}</h2>
      {{ .Content }}
    </article>
  {{ end }}
{{ end }}

Source: Hugo documentation - blocks

However, why should you use blocks instead of basic and straightforward partials? Before anything, be careful. Partials still make sense for many usages, so I’m not saying you should replace all occurrences with a block.

In other words, a better question would be, “when should you use blocks?”

When

People often say blocks help prevent repetition, but partials can do it too. IMHO, blocks are more appropriate than partials when you need to share code between several templates with the same opening and closing tags but different contents.

For example, you don’t want to include the same partials over and over in all templates:

{{ partial "header.html" . }}
<!-- code of the template -->
{{ partial "footer.html" . }}

It’s a striking example of useless repetition. Instead, you can call those partials in layouts/_default/baseof.html, add a block main in the base template and only make necessary changes in your template:

{{ define "main" }}
<!-- code of the template -->
{{ end }}

Conclusion

Both blocks and partials help prevent repetition and respect the Don’t repeat yourself (DRY) principle, but blocks are cleaner when you only need to override a small part of the base template.

It’s not a matter of performance, as Hugo has a robust internal cache API for partials, but it’s more convenient for maintenance.

This block API is genuinely interesting. You can find similar approaches in templating languages such as Twig.