How to add CSS from a Theme Component?

Hi there!

I’ve been using Theme Components to build this shortcode. That’s an awesome feature!

However, the CSS required by the Component is now hardcoded in the partial file, is there a more elegant way to inject custom CSS from a child theme?

(Note that I would like this Component to be as theme-agnostic as possible)

A second drawback of the actual implementation is that the CSS is injected each time the Shortcode is used. (if the Shortcode is called 5 times on the same page, the CSS is injected 5 times too!).
Any hint to improve that?

Best regards

the CSS required by the Component is now hardcoded in the partial file, is there a more elegant way to inject custom CSS from a child theme?

Here’s one way, using Hugo Module Mounts to the assets/ directory and then using the Resources related functions.

Here’s the part that does the injection of CSS based on a site parameter.

Demo site


Reference

3 Likes

This should be avoid with this method :

{{- if not ($.Page.Scratch.Get "noticecount") -}}
    <style type="text/css">.notice{padding:18px;}</style>
{{- end -}}
{{- $.Page.Scratch.Add "noticecount" 1 -}}
1 Like

Nice, I’ve been thinking of modifying some modules and a theme to use the embedded <style>, so this is good to know.

1 Like