Hugo: Linking to the static directory

I don’t know why this is so difficult. Hugo provides a static directory where you can put stuff that is directly copied to your web directory. In theory you can have links [A link]("/file.pdf") and if you the file static/file.pdf in your Hugo project base directory then all is well.

If your homepage has its root at some other location than the root, say example.com/Hugo rather than just example.com, then this does not always work. I really don’t understand why.

After googling I found this solution that creates a special short code. You use [A link]({{< static "/file.pdf" >}}) blah

You need to create the file layouts/shortcodes/static.md with the following content:

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

It turns out that this rather long winded approach has its advantages. If you put all your papers in static/papers/ then you can create a shortcode layouts/shortcodes/paper.md :

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

You can the create links to your papers as :

[This paper]({{< paper "2017_ICTAI.pdf" >}})

Assuming that 2017_ICTAI.pdf is in your papers directory.

Incidental, if you are having trouble showing unexpended short codes in code blocks, then this thread will help.

Justin Pearson
Justin Pearson
Docent in Computing Science

Lecturer and researcher at Uppsala University.