Linking to static files with Hugo

I have this in config.toml:

baseURL = "https://my-username.github.io/blog/"

and there is a static file at static/img/foo.png.

Now, in content/posts/bar.md, I have the following content:

---
title: "Bar"
---

![foo](img/foo.png)

The picture isn’t showing after I started the hugo server, so I inspected elements, and found out that Hugo generated the following URL for it:

http://localhost:1313/blog/posts/bar/img/hireme.png

This is not what I expect; it should be

http://localhost:1313/blog/img/hireme.png

When I use ![foo](/blog/img/foo.png), the picture is displayed correctly, but this is quite strange: /blog/ is part of baseURL, why do I need to type it again?

because when you use the slash in front of your link reference, it takes that from the root of the domain, which is everything before the first / in your baseURL. without the / in your link reference, it is a link relative to the current document. It’s about syntax for accomplishing different things, not trying to complete the baseURL.

I got frustrated by this too and ended up creating a static shortcode that works like the ref and relref built-ins. Basically it takes the path and, if it doesn’t have a protocol in front, appends it to the BaseURL.

You can download a copy if you want, or the code is below:

{{- .Scratch.Set "path" (.Get 0) -}}
{{- if hasPrefix (.Scratch.Get "path") "/" -}}
  {{- .Scratch.Set "path" (slicestr (.Scratch.Get "path") 1) -}}
{{- end -}}
{{- .Scratch.Get "path" | absLangURL -}}

All but the last line is there to remove a leading "/", I think because it caused issues. You can replace absLangURL with a different function, if you prefer.

Usage: ![foo]({{< static "img/foo.png" >}})