Skip to content

How to add YAML highlight in Highlight.js?#

Haters gonna hate YAML, thats for sure. I am on the other hand in love with YAML; when one have to manually write/append config files I find YAML easier than JSON (and you have comments too).

Ansible, various static-site-generators and quite a lot of opensource tools use YAML syntax for the configuration purposes.
But still, YAML syntax highlighting is not a part of the Common languages shipped with highlight.js compiled package.

Hugo also uses the hljs to colorize code snippets, but it uses the default pack of languages that lacks YAML support.

Look at this greyish snippet, looks ugly.

---
- name: Prepare linux virt host
  gather_facts: no
  hosts: localhost
  tasks:
    - name: Include packages/services to install/set
      include_vars: main.yml

Luckily, we can add custom languages using Cloudflare CDN collection of pre-built packages.

To do so, add this config portion to your Hugo' config.toml:

# double check, that you have 
# syntaxHighlighter = "highlight.js" in your config.toml

# note, [[params.customJS]] is nested under [params] section
  [[params.customJS]]
      src = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/languages/yaml.min.js"
      integrity = "sha256-tvm0lHsuUZcOfj/0C9xJTU4OQx5KpUgxUcAXLX5kvwA="
      crossorigin = "anonymous"
      async = true
      defer = true

And now our YAML looks a bit better:

---
- name: Prepare linux virt host
  gather_facts: no
  hosts: localhost
  tasks:
    - name: Include packages/services to install/set
      include_vars: main.yml

I changed the style-*-.min.css property to highlight string portions in green, instead of dark blue. A proper way would be to use a custom HLjs theme, but building it in Tranquilpeak theme is kinda tedious, so I picked up a shortcut changing the compiled css instead:

# change the color code for this class
# in my case I changed to #a5c261
.codeblock .string,figure.highlight .string{color:#a5c261}

Thanks to Tranquilpeack for Hugo theme maintainer, who shared with me this option for custom highlighting

PS. Since the method to load custom JS described in this article has a bug when it comes to Chrome browser, I changed the way Hugo loads custom JS as suggested in the referenced issue.

Comments