How to load fonts conditionally in Hugo?

Hey guys this may be beyond the scope of hugo and not related but I have a static/plugins/font.css file that contains all my fonts across all my projects / themes. I import my fonts.css file in all my headers but that’s wasting resources on the themes that don’t use them since they download to the page anyways, is there a way to programmatically include the fonts in a way that only builds with the fonts I use for a theme? An example of one of my fonts:

@font-face {
  font-family: BigShouldersDisplay;
  src: url("../../fonts/BigShouldersDisplay-Medium/BigShouldersDisplay-Regular.eot"); /* IE9 Compat Modes */
  src: url("../../fonts/BigShouldersDisplay-Medium/BigShouldersDisplay-Regular.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
       url("../../fonts/BigShouldersDisplay-Medium/BigShouldersDisplay-Regular.woff") format("woff"), /* Modern Browsers */
       url("../../fonts/BigShouldersDisplay-Medium/BigShouldersDisplay-Regular.ttf")  format("truetype"), /* Safari, Android, iOS */
       url("../../fonts/BigShouldersDisplay-Medium/BigShouldersDisplay-Regular.svg#BigShouldersDisplay-Regular") format("svg"); /* Legacy iOS */
}```

How are you loading font.css through your themes? Are you using themes made by the Hugo community or have you made custom themes yourself?

I’ve made them.

	{{ range $data.data.plugins_css}}
        {{ if .enabled }}
		    <link rel="stylesheet" type="text/css" href="{{ .Site.BaseURL }}{{ .link }}">
        {{ end }}
	{{ end }}

I am going to give you an outline without writing specific code due to lack of time.

  • First you would need to specify which fonts you need under the params table of the config
  • Then move the fonts stylesheet to the assetDir and call it as a resource in your templates by using the ExecuteAsTemplate method.
  • Finally within the stylesheet you need to set conditions to selectively include the fonts based on the values of the parameters set in the config.

I didn’t know about loading resources, thank you!

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