
Sarah COUDERT
April 07, 2023 - 12:56 EST
Syntax highlighting for code block in trix editor
When I arrived, all was gray.
When I first started to develop this this blog, I started using a Trix WYSIWYG editor for rich Action Text, but there was no syntax highlighting, which bummed me out... it looked like this :
def no_colour puts "I'm nothing but sadness" end
Ugly, right?
But then I found a tutorial by Andre from BigDumbWeb, but it was for an older Rails version and didn't use Stimulus/Hotwire. No biggie, though! I wanted to learn Stimulus controllers anyway.
But then I found a tutorial by Andre from BigDumbWeb, but it was for an older Rails version and didn't use Stimulus/Hotwire. No biggie, though! I wanted to learn Stimulus controllers anyway.
And then, all became colorful again.
So here's the code I whipped up to make it happen, in my "app/views/posts/_post.html.haml" :
%div{id: 'trix-parent', data:{post_target: "body"}} %p{class: 'mb-6 text-gray-600 dark:text-gray-400' } = post.body lang-haml
And the real deal, the "app/javascript/controllers/post_controller.js" :
import { Controller } from '@hotwired/stimulus' export default class extends Controller { static targets = ['body'] connect () { this.bodyTarget.querySelectorAll('pre').forEach(function(preElement) { const regex = /(?!lang\-\\w\*)lang-\w*\W*/gm; const codeElement = document.createElement('code'); if (preElement.childNodes.length > 1) { console.error('<pre> element contained nested inline elements (probably styling) and could not be processed. Please remove them and try again.') } let preElementTextNode = preElement.removeChild(preElement.firstChild); let language = preElementTextNode.textContent.match(regex); if (language) { language = language[0].toString().trim(); preElementTextNode.textContent = preElementTextNode.textContent.replace(language, ''); codeElement.classList.add(language, 'line-numbers'); } codeElement.append(preElementTextNode) preElement.append(codeElement) Prism.highlightAll(); }) } } lang-javascript
Now, when I look at a post, it looks like this 😄
def colour puts "Hey, I'm in color!" end lang-ruby