I have a css file in my assets/ and I want to include an image from the static/ folder
I use this:
background-image: url("/background.png")
The only issue is that my base url in my config.toml and my prod env is https://mysite.com/blog
So instead of looking for https://mysite.com/blog/background.png
it looks for https://mysite[.]com/background.png
Any idea how I could fix this?
There are a few ways to handle this, but my preference is to:
-
Place images that arenβt specific to a page in the assets
directory, then capture them as needed with the resources.Get
function.
-
Place template code in your CSS file, then capture it as a resource with the resources.Get
function, then pass it through the resources.ExecuteAsTemplate
function.
assets/
βββ css/
β βββ main.css
βββ images/
βββ background.png
assets/css/main.css
{{ $i := "" }}
{{ with "images/background.png" }}
{{ with resources.Get . }}
{{ $i = . }}
{{ else }}
{{ errorf "Unable to find %s in the assets directory." . }}
{{ end }}
{{ end }}
body {
background-image: url("{{ $i.RelPermalink }}");
background-size: cover;
background-repeat: no-repeat;
}
layouts/_partials/css.html
{{ with "css/main.css" }}
{{ with resources.Get . }}
{{ with resources.ExecuteAsTemplate "css/main.css" $ . }}
{{ if hugo.IsDevelopment }}
<link rel="stylesheet" href="{{ .RelPermalink }}">
{{ else }}
{{ with . | minify | fingerprint }}
<link rel="stylesheet" href="{{ .RelPermalink }}" integrity="{{ .Data.Integrity }}" crossorigin="anonymous">
{{ end }}
{{ end }}
{{ end }}
{{ else }}
{{ errorf "Unable to find %s in the assets directory." . }}
{{ end }}
{{ end }}
Then call the partial from your base template:
{{ partialCached "css.html" . }}
1 Like