Code syntax highlighting with Rails and Trix

2024-01-08 23:25

One of my goals for this blog was to add syntax highlighting for code. This blog is a standard rails project so I want to stick to defaults as much as possible.

Rails comes with a rich text feature called Action Text that uses the Trix editor client side to generate the rich text.

For the actual syntax highlighting, I'm using highlight.js.

The Trix editor has a code tag, but it's just a standard <pre>. By default highlight.js looks for a <code> tag inside of a <pre> tag like such:

<pre><code>print("hello world")</code></pre>

Unfortunately, Trix doesn't seem to support (at least from my research) nested custom elements like this. Luckily we can configure a custom CSS selector in highlight.js to target the pre tags within the Trix rich text div.
hljs.configure({"cssSelector": ".trix-content pre"});

Rails also uses turbo rails by default which means every page click isn't a full refresh so we have to listen to page load event to trigger highlight.js to highlight our elements.
document.addEventListener("turbo:load", function() {
Now hopefully you should see some simple syntax highlighting on this page.