I’m about 2 weeks into my walk with Hugo and love it.
I spent all day trying to figure out how to comply with Content-Security-Policy and still allow a customer to edit a Data .yml file to change the background image on their index.html.
Before applying the Content-Security-Policy I was using style=“background-image: URL({{ VARIABLE }}” and it worked great.
Then after applying Content-Security-Policy, my image didn’t show up and in the developer tools, I had an error in the console informing me I was violating the Content-Security-Policy. Yes, you can get rid of the error bypassing one of the policies, but if you do, you’re opening a security crack that Content-Security-Policy is supposed to protect viewers of your site.
After hours and hours of researching, I finally ran into this page.
https://gohugo.io/hugo-pipes/resource-from-template/
I created this assets/css/dynamic.scss file.
{{ $data := index .Site.Data }}
{{ if $data.homepagehero.hero.enable }}
{{ with $data.homepagehero.hero }}
.bg-hero {
background-image: url("{{ .bg_image | relURL }}");
}
{{end}}
{{end}}
Then in my theme /layouts/partials/head.html
{{ $sassTemplate := resources.Get "css/dynamic.scss" }}
{{ $dstyle := $sassTemplate | resources.ExecuteAsTemplate "css/dynamic.scss" . | resources.ToCSS }}
{{ $dstyle := $dstyle | fingerprint | resources.PostProcess }}
<link rel="stylesheet"
href="{{ $dstyle.RelPermalink }}" integrity="{{ $dstyle.Data.Integrity }}">
Now in an HTML file, I can use the dynamically created CSS class (bg-hero) to assign a customer-defined background image.
<div class="bg-hero bg-no-repeat bg-cover"></div>
This also makes my website compatible with Content-Security-Policy.
Hope this helps someone else.
@bep I tagged you to show another real-world use case for this outstanding feature.