Generated image
|| #resource #hugo

Reusing Partials in Hugo

Avoid code duplication by reusing Hugo partials

Problem

When building static websites with #hugo there are two kinds of "re-usable content blocks": shortcodes and partials.

The problem is that these are not interchangeable. Shortcodes can only be used when writing markdown files, while partials can only be used in HTML files.

Since these code blocks often represent the same content/structure, I want a way to re-use them.

Solution

1. Partial definition

partials/text/exteralLink.html

{{ $link := .Link }} {{ $anchorText := .Text }}

<a href="{{ $link }}" target="_blank"> {{ $anchorText }} </a>

2. Shortcode definition

shortcodes/text/exteralLink.html

{{ partial "text/externalLink" (dict "Link" (.Get "link") "Text"
.Inner) }}

3. Example use of the shortcode in a markdown file

{{< text/externalLink link="https://example.com" >}}
Example website
{{< /text/externalLink >}}

Details

The code blocks above describe a way to avoid code duplication between the two by using the partial as the system of record of the HTML code and have the shortcode reference it.

The one little trick to make this work correctly is to make sure any variables get passed down correctly - since they use slightly different formats. In the code above I use a dict object to take the variables from the shortcode and pass them to the partial. I can then reference those variables in the partial in the same way whether it is referenced in an HTML template or from a shortcode.


Maybe try another one?

Simple Startup Script Setting up a simple service with SystemD
2022.10.08
Encrypted LUKS Container Create an encrypted volume on linux using LUKS
2022.05.24
Git Log with Changed Files Show a more complete git log with details about changed files
2022.09.26