I’d like to generate the smallest possible inlined css in each page, and if possible then I’d also like to write the css in the same file as the partials/shortcodes html code.
I imagined achieving it like this:
_default/baseof.html
<html>
<head>
<meta />
<meta />
<title>{{ .Title }}</title>
{{ block "styles" . }}
{{ end }}
</head>
<body>
{{ block "main" . }}{{ end }}
{{ partial "footer.html" . }}
</body>
</html>
{{ define "styles" }}
{{ partial "inline-styles.html" . }}
{{ end }}
partials/footer.html
{{ $footerStyles := `
footer {
background-color: red;
}
` | safeCSS }}
{{ .Store.Set "footerStyles" (slice $footerStyles) }}
<footer>Hello footer</footer>
partials/inline-styles.html
{{ $footerStyles := .Store.Get "footerStyles" }}
{{ $messageStyles := .Page.Store.Get "messageStyles" }}
{{ $styles := slice }}
{{ if $footerStyles }}
{{ $styles = $styles | append $footerStyles }}
{{ end }}
{{ if $messageStyles }}
{{ $styles = $styles | append $messageStyles }}
{{ end }}
{{ if gt (len $styles) 0 }}
{{ $combined := delimit $styles "" }}
<style>
{{ $combined | safeCSS }}
</style>
{{ else }}
<pre>No styles collected</pre>
{{ end }}
When I develop locally then it kinda works (except for initial load) when I navigate around (guess because of cache), but when I build the project then it shows ‘No styles collected’.
If I just call {{ partial “inline-styles.html” . }} at the bottom after all my partials/shortcodes then it also work, but I want the styles inside the head.
I tried to make a global variable at the top and add styles to that (didn’t work, but maybe I did it wrong), and I’m thinking one potential solution would be to define all the required styles inside the content frontmatter, but I don’t want to do that since it would become messy compared to just automatically detecting it based on which partials/shortcodes appear on the page.
Also okay with using tailwindcss as long as the only the used styles for that particular page are rendered in the head, but think they would be even more complicated to do.
Any suggestions would be much appreciated <3