Assets image as background

Hello :slight_smile:

I just started to use Hugo, but I feel like I’m already pretty comfortable with navigating the documentation. However, I could not find anything for my problem.

In my understanding, most assets should be delivered through the defined assets folders and not live in the static folder. I’m currently trying to rewrite a theme for my purposes and wanted to move - while I’m at it - most stuff into the assets folder and found an obstacle here.

This is the original code to embed a website logo:

  <a href="{{ .Site.BaseURL }}">
{{ if (isset .Site.Params "gravatar") }}
  <div id="logo" style="background-image: url(https://www.gravatar.com/avatar/{{ md5 .Site.Params.gravatar }}?s=100&d=identicon)"></div>
{{ else if (isset .Site.Params "logo") }}
  <div id="logo" style="background-image: url({{ .Site.Params.logo | absURL }})"></div>
{{ else }}
  <div id="logo" style="background-image: url({{ "images/logo.png" | absURL }})"></div>
{{ end}}

and I wanted to change the last part to

{{ else }}
{{ $image := resources.Get "images/logo.png" }}
  <div id="logo" style="background-image: {{ $image.RelPermalink }}"></div>
{{ end}}

This resolves however to
<div id="logo" style="background-image: ZgotmplZ"></div>
while the same tag embedded as normal image results in
<img srcset="http://localhost:1313/images/logo.png"> as expected.

Assets directory is defined and works with everything else but this special case. Did I miss something?

ZgotmplZ is a special value indicating that unsafe content has reached a CSS, JS, HTML or URL context during the execution of a Hugo/Go template.

In your case you need to use the safeHTMLAtr function to fix the error:
style="background-image: {{ $image.RelPermalink | safeHTMLAttr }}"

Also there are more functions for different contexts: safeHTML, safeCSS, safeJS, safeURL

1 Like

It worked with safeCSS. Thank you! I thought this was some kind of ID for the picture and did not search for it.

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.