Two different Chroma styles in one post?

My current posts contain some material I’d like to present as source code (or at least, with some sort of monospace font). But there are different sorts of material: some are examples; some are actual source code. And I’d like to visually differentiate them.

The Chroma style is set in my base configuration config.toml. Is there a way I can use two (or more) different styles and pick a particular one for a particular bit of code?

Thank you!

  1. Generate the styles of your code highlighting style choice (one file per style). See here

  2. Use SCSS for your stylesheet generation

    A sample from my own styles:

    .light {
      @import 'plugins/syntax/light';
    }
    .dark {
      @import 'plugins/syntax/dark';
    }
    
  3. Somehow (I did not think this that far through, but there should be ways to add a class to your highlighting markup or shortcode) add a class to your code blocks.

Edit to add:

  1. Set your config so that the highlighting features do not use inline CSS for the highlights.
    [markup.highlight]
    noClasses = false
    

config

[markup.highlight]
style = 'monokai'

markdown

```bash
if [[ "${foo}" = "a" ]]; then
  echo "${foo}"
fi
```

```bash {style=perldoc}
if [[ "${foo}" = "a" ]]; then
  echo "${foo}"
fi
```

```bash {style=friendly}
if [[ "${foo}" = "a" ]]; then
  echo "${foo}"
fi
```

result

If you always want to use a particular style for a given language, you could create a code block render hook.

layouts/_default/_markup/render-codeblock.html

{{ $styles := dict
  "bash" "fruity"
  "go"   "perldoc"
  "html" "friendly"
}}
{{ $options := merge .Options .Attributes }}
{{ with .Options.style }}
  {{ $options = merge $options (dict "style" .) }}
{{ else }}
  {{ with index $styles .Type }}
    {{ $options = merge $options (dict "style" .) }}
  {{ end }}
{{ end }}
{{ (transform.HighlightCodeBlock .  $options).Wrapped  }}

If the info string contains a style attribute (as shown in the examples above), it will take precedence over the styles map.

If the info string does not contain a style attribute, and if the language is not in the styles map, the default style in site configuration will be used.

See https://gohugo.io/templates/render-hooks/#render-hooks-for-code-blocks

3 Likes

Many thanks! That looks surprisingly easy and straightforward. I actually do my Hugo blog writing in emacs, using Kaushal Modi’s excellent ox-hugo package. But I think your examples would easily work.

That looks fairly straightforward - many thanks indeed! I’ll try it out and see how I go.