I’m building a shortcode. So far so good, even with my poor HTML/CSS knowledge.
In my case, I’m creating a shortcode to create a format for some specific content. I have HTML code and CSS styles. I would like to know the best practices in order to place files in correct places. I’m aware of this question, but I would like to get more information, if possible.
HTML code is clear for me: I put it in layouts/shortcodes/my-shortcode.html.
But what about:
Specific fonts. I want to give stylized fonts with new ones like:
CSS files. Similar to 1, I want to obtained stylized layouts using my shortcode. Where should I put my CSS styles? Previous answer points to be self-contained, which makes sense. Any other ideas like files in the same folder?
What about any static content like images? This one is not clear to me. The same folder?
Are you planning to share this shortcode with other people / sites or is it unique to your site? Consider if specific fonts are important to your shortcode’s functionality. If they are not, just include the fonts in your custom theme. Static files should be located within static, either in the root folder or themes/...theme-name.../static/ as noted here: https://gohugo.io/content-management/static-files/
A shortcode alone is contained within itself. If you need to include assets, partials etc you need to structure it like a Theme Component, just like the example of hugo-notice above.
The author of hugo-notice decided to use inline SVG images and inline CSS, which has several shortcomings, but makes it easy to drop in without manual modification of other partials. Loading specific fonts however, has to be done by either manual modification of the header, or load them with JavaScript.
I would add some form of scratch variable that is set to true the first time a short code is used. Then add in the output of the shortcode the loading of JS or CSS inline, if your scratch variable is not set, like this:
CSS should be able to be added likewise, with link instead of script and a rel-attribute. I would expect some “flash of content” before the additional scripts/styles are loaded, because they are only loaded after the page loaded fully. Also, if you use external libraries like jQuery you need to have an eye on the order that things are loaded and check if they are available at that point. defer and async are your friends.
In the long term, if you for instance use some form of hook system, you could check for the existence/use of a shortcode in a page via .HasShortcode:
I never tested that though… might play around with it some time.