Simple Icons integration with Hugo modules

Created:

Updated:


Simple Icons is a free and open source icon set for popular brands including social media sites such as Twitter, YouTube, Twitch, GitHub, and so on. This is a perfect component for getting social media icons.

Usually to make use of this icon set in Hugo, you would have to download each icon you need. Luckily, there’s an easier way to make use of the set with Hugo modules. In the future, Hugo will have an easier way to integrate with JavaScript modules. [1]

To get started, simply initialize your Hugo site as a Hugo module with hugo mod init $HUGO_MOD_NAME where $HUGO_MOD_NAME is simply the name of the Hugo module which could be anything. For example, if you host your Hugo site on GitHub pages, you might want to name your module like github.com/$USER/$HUGO_SITE_REPO.

Then, add the Simple Icons repo as a dependency module in your site configuration. The following configuration gets the icon set and the metadata and places them at assets/icons and data/simple-icons.json respectively.

[[module.imports]]
  path = "github.com/simple-icons/simple-icons"
  [[module.imports.mounts]]
    source = "icons"
    target = "assets/icons"
  [[module.imports.mounts]]
    source = "_data/simple-icons.json"
    target = "data/simple-icons.json"

Onto the interesting point which is using the icons itself. Since the icon set is stored in the assets folder, we can then use it in our templates.

{{ $github_icon := resources.Get "icons/github.svg" }}
{{ $github_icon.Content | safeHTML }}

And the SVG source will be applied inline to the resulting page. This opens up a lot of uses with the icon set.

Let’s reimplement the configurable list of contacts with added feature of adding an icon from the set with each key serves as the icon to be displayed.

<address>
{{- range (sort $.Site.Data.contacts "weight" "asc") -}}
<a rel="me" href="{{ .url }}" aria-contact="{{ .name }}">
    {{ $location := printf "icons/%s.svg" .id }}
    {{ with resources.Get $location }}{{ .Content | safeHTML }}{{ end }}</a> |
{{- end -}}
</address>

Unfortunately, this doesn’t take account for missing icons so a fallback would be handy. For now, we’ll use text as our fallback even though it’s not going to be pretty.

<address>
{{- range (sort $.Site.Data.contacts "weight" "asc") -}}
<a rel="me" href="{{ .url }}" aria-contact="{{ .name }}">
    {{ $location := printf "icons/%s.svg" .id }}
    {{ $icon := resources.Get $location }}
    {{ if (countrunes $icon.Content) }}
        {{ .Content | safeHTML }}
    {{ else }}
        {{ .name }}
    {{ end }}
</a> |
{{- end -}}
</address>

1. Or integrating with NPM which Hugo certain has more support in the upcoming version.

Available in other languages: | English | Tagalog |

© 2022 Contentful