How to load custom fonts from assets

Hello all,

I am trying to load a custom font from assets directory
The font is not available on Google Fonts
And the font files are not being copied to public/fonts directory

I attempted to load the font using Hugo’s resource management:

{{ $font := resources.Get "fonts/your-font.woff2" }}

<link rel="preload" href="{{ $font.RelPermalink }}" as="font" type="font/woff2" crossorigin>`Preformatted text`

What’s the correct way to handle custom fonts in Hugo?
There is some solution but only with previous Hugo version using “static”, but no way to have a similar behavior.
Is there a specific configuration needed to copy font files to the public directory?

Any guidance would be appreciated. Thanks!

assets/
├── fonts/
│   └── your-font.woff2
└── sass/
    └── main.scss

Placing this with the head element of the base template works for me:

{{ with resources.Get "fonts/your-font.woff2" }}
  <link rel="preload" href="{{ .RelPermalink }}" as="font" type="font/woff2" crossorigin>
{{ end }}

If you have many fonts you can do this:

{{ range resources.ByType "font" }}
  <link rel="preload" href="{{ .RelPermalink }}" as="font" type="{{ .MediaType.Type }}" crossorigin>
{{ end }}
2 Likes

Perfect.

That could be explained in:

No way to find by myself.
Thank you.

How is that fundamentally different from the OP’s approach – I’m probably overlooking something again, but they were publishing the resource, too. The with is setting the dot and making the code more robust, yes. But I don’t understand why the approach with a $font variable shouldn’t work as well.

Given that the file actually exists, they do the same thing. Assuming the OP didn’t change anything between tests, both work.

1 Like

I - really - did - not - understand - what - you - said.
→ Probably a topic for Hugo experts.

Whom are you referring to?

Your code was this

And @jmooring suggested this

There is no fundamental difference between these two implementation. Except that the second one will not cause an error if the resource (“fonts/your-font.woff”) does not exist. The with sets the dot to the result of resources.Get "…". Therefore, you use .RelPermalink in your href attribute.
Your code used the variable $font to store the result of resources.Get "…" and consequently used $font.RelPermalink in the href attribute.
Same difference.

But: The concept of “dot” is central to Hugo templating. It is most certainly not

but essential knowledge for everyone using Hugo. Better get yourself acquainted with it. For example by reading

Ohhh sorry my bad for the missunderstanding.
Regarding this code, the solution you provided works perfectly, and I was able to set up my fonts as intended.

However, I’m still confused about the following discussion, particularly this comment:

I’m still confused about this part.
Btw, thank you for your help.
Yesterday, I did some great progress in my project.