Prism Syntax Highlighting for Craft CMS

Tutorial for using Prism syntax highlighting on your code blocks in Craft CMS. Very simple setup for assigning languages to code used in entries and displaying them as coloured syntax on your website.

My setup is a Craft CMS v3, Laravel Mix with webpack and Tailwind. I wanted something simple and not be dealing with importing and merging styles with Tailwind etc. I wanted the same Prism Theme throughout my site, and although there are Craft CMS plugins available (See Further Reading), I was trying to keep my plugins to a minimum and not deal with complexity.

Whats is Prism?

Prism is 'a lightweight, extensible syntax highlighter' and is what you see styling all my code examples below.

Packages needed

You can install all of these in one fell swoop by running the following in your project root.

npm install prismjs babel-plugin-prismjs prism-themes

Adding Prism

Add the following to your main Javascript file to pull in Prism. In my case its app.js

import Prism from 'prismjs';

Prism.highlightAll();

Babel Prism Plugin

To use the prismjs babel plugin effectively you need to add a file called .babelrc in the root of your project. Add or remove any languages you don't need. Plugins refer to Prism Plugins. The theme is what you pick from prism themes. For example, if you wanted the recently popular Synthwave '84 Theme then just swap out shades-of-purple with synthwave84. Recompile your assets and you have a new theme. Easy as that.

{
  "plugins": [

	  ["prismjs", {
		  "languages": ["javascript", "css", "twig", "php"],
		  "plugins": [],
		  "theme": "shades-of-purple",
		  "css": true
	  }]
	]
  }

Craft CMS Matrix Field

I am using a Matrix field to create a Content Builder for my entries. For my code block, it's pretty standard other than a language field as a dropdown which mimics the languages I added to my .babelrc file

More on Content Builder methods here, here and here.

If you are going the Redactor route then I suggest reading the articles below in Further Reading

Code block for Matrix Field Craft CMS
Matrix field layout for code block
<div class="code-block mx-auto py-6">
	<pre><code class="language-{{ block.codeLanguage }}">{{ block.codeBlock }}</code></pre>
</div>

And that's basically it! Well, your experience may fare based on your own set-up. But leave a comment if having trouble and I'll try and help out.

I'm a no-nonsense, experienced website developer who works with Content Management Sytems and specializes in Craft CMS.

Lets Talk Today!