How to add Syntax Highlighting to a Statamic Site

Published December 31st, 2019
3 minute read
Warning!
This was written over two years ago, so some information might be outdated. Frameworks and best practices change. The web moves fast! You may need to adjust a few things if you follow this article word for word.

Note: This applies to Statamic version 3+. In v2 the file locations will be in your theme.
We'll cover how to add syntax highlighting to code blocks in Statamic v3 using Prism. With a couple quick steps you'll have your code blocks looking spiffy!
My preferred client side highlighter is Prism because it's lightweight and easy to use.

First, we'll want to install prism with npm:

1npm i prismjs
1npm i prismjs

Next, in your resources/js/app.js file, add the following lines:

1import Prism from 'prismjs'
2import 'prismjs/themes/prism-tomorrow.css' // see other themes in the prism docs
3import 'prismjs/components/prism-markup-templating'
4import 'prismjs/components/prism-php'
5import 'prismjs/components/prism-bash'
6import 'prismjs/components/prism-css'
7import 'prismjs/components/prism-json'
8import 'prismjs/components/prism-javascript'
9import 'prismjs/components/prism-yaml'
10Prism.highlightAll()
1import Prism from 'prismjs'
2import 'prismjs/themes/prism-tomorrow.css' // see other themes in the prism docs
3import 'prismjs/components/prism-markup-templating'
4import 'prismjs/components/prism-php'
5import 'prismjs/components/prism-bash'
6import 'prismjs/components/prism-css'
7import 'prismjs/components/prism-json'
8import 'prismjs/components/prism-javascript'
9import 'prismjs/components/prism-yaml'
10Prism.highlightAll()

This imports Prism, a theme (prism-tomorrow), and the languages we want to use. If you use something like SASS or LESS, be sure to look at the available prism languages and include any others you need on the Prism docs.

Now you can run npm run dev and you should see your markdown code blocks with some nice formatting.

*If you don't, you probably just need to format your code blocks. For example,

1```php
2 
3# or
4 
5```bash
1```php
2 
3# or
4 
5```bash

You can also use CSS to style prism, for example if you wanted to add language types to the blocks (like I have at the top right). Here's my styles if you'd like them.

Enjoy this article? Follow me on Twitter for more tips, articles and links.
😢 Awww, nobody has liked or mentioned this on Twitter yet.

Want Updates?

Sign up here if you want to stay in the loop about new articles or products I'm making.
I'll never spam you. Unsubscribe at any time.
Copyright ©2024 Austen Cameron