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 docs3import '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 docs3import '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```php23# or45```bash
1```php23# or45```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.