By GolferHD September 13, 2023

Setup
In this tutorial, we’ll delve into the process of creating reusable SVG components in Hugo. We’ll start by crafting an svgImage.html
partial, which will be the foundation for our svgButton.html
partial. By the end of this guide, you’ll have a flexible SVG button component that can be easily customized and integrated into your Hugo site.
Execute
Motivation
I wanted to add a clickble Linktree icon similar to my Instagram and Twitter buttons, but unfortunately there’s no Linktree icon in FontAwesome. No problem, we’ll create our own.
Prerequisites
- A working Hugo site.
- Basic knowledge of HTML.
- SVG images you wish to use.
Step 1: Setting Up the svgImage.html Partial
This partial will be responsible for rendering SVG images. The idea is to make SVG inclusion more streamlined and efficient.
- Navigate to your Hugo project directory.
- Inside the
layouts
directory, ensure there’s a folder namedpartials
. - Create a new file named
svgImage.html
within thepartials
folder.
svgImage.html:
{{ $svgPath := printf "static/svg/%s.svg" . }}
{{ with readFile $svgPath }}
{{ . | safeHTML }}
{{ else }}
<p>Error: SVG not found.</p>
{{ end }}
This code fetches the SVG content from the images
directory, minifies it, and then renders it safely.
Credit: This approach is inspired by Utkarsh Verma’s method.
Step 2: Crafting the svgButton.html Partial
Now, we’ll create a button that incorporates the SVG image from our svgImage.html
partial.
- Still within the
partials
folder, create a file namedsvgButton.html
.
svgButton.html:
<a href="{{ .url | default .Site.Params.linktree_url }}">
<div style="color: {{ .color | default "#ffffff" }}; fill: currentColor; width: {{ .width | default "12em" }}; display: {{ .display | default "block" }};">
{{ partial "svgImage.html" (.icon | default "linktree") }}
</div>
</a>
Step 3: Implementing the SVG Button in Your Content
With the partials set up, you can now easily integrate the SVG button into your content or other templates.
- Custom Style:
{{ partial "svgButton.html" (dict "color" "#ffffff" "width" "12em" "display" "inline-block" "icon" "linktree") }}
- Another Custom Style:
{{ partial "svgButton.html" (dict "color" "#6bae79" "width" "8em" "icon" "linktree") }}
These implementations allow you to customize the SVG button’s appearance by passing different parameters to the svgButton.html
partial.
Finish
By leveraging Hugo’s powerful partials system, we’ve now crafted a reusable SVG button component that can be effortlessly integrated across your site. This approach ensures a consistent look and feel, while also streamlining the content creation process.
Drive and Dream,