Static Resource URIs

Hey, Hugo n00b here with what’s hopefully a simple question. I’m putting my first theme together, and I’m wondering how y’all handle static resource paths? I know that by default if I include a relative path in my HTML it’ll get echoed out into the result directly, so I’ve found myself doing things like

href="{{.Site.BaseURL}}css/style.css"

in my partials to make sure they’ll work at different levels in the URI hierarchy, but I’m wondering if there’s any nicer way to handle these paths? Especially in my CSS, which isn’t processed by Hugo so I can’t even do that. I’ve been using full paths with a leading slash, which works fine for my use case, but it would break if I tried to use the same theme on a site that was getting deployed to a subdirectory instead of the root of a domain.

This seems like a common enough issue that it’s got to have a simple solution that I’m missing, but I wasn’t able to find anything in the docs. Any ideas?

You might run into trouble if you don’t have a / between {{.Site.BaseURL}} and css/style.css. You’d have to add a trailing slash to your BaseURL in your config.toml.

But as for static resource paths, I’ve been using relative paths like so: href="/css/main.css"
I’ve not run into trouble using relative paths when typing them correctly.

Ah, yeah, my base URL includes a trailing slash. Not sure if that’s ideal or not. The leading slash technique works for me in CSS as long as I deploy to the root of a domain (which, thankfully I am), but if I were ever to try to use it on a site whose base URI was, say, www.something.com/prefix/, it’d fall down unless I added the /prefix/ to every URI in the theme

I recommend using either relURL or absURL funcs:

Those will handle the trailing slashes problem.

1 Like