Adding code styling to your Ghost blog - in 3 minutes
When I first started using Ghost, I was surprised by the lack of code highlighting. Thankfully, it's quite easy to implement. Another fact I didn't like was that the code was hard to distinguish from the blog theme.
Today we'll install PrismJS, a code highlighting library. Following these steps will have code highlighting in your site within 3 minutes.
Code highlighting
1. To start, go to your site settings into the Code Injection part.
- Add the following bit of code to your Site heading text area:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism.min.css" integrity="sha512-tN7Ec6zAFaVSG3TpNAKtk4DOHNpSwKHxxrsiw4GHKESGPs5njn/0sMCUMl2svV4wo4BK/rCP7juYz+zx+l6oeQ==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- Add the following bit of code to your Site footer text area:
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js" integrity="sha512-9khQRAUBYEJDCDVP2yw3LRUQvjJ0Pjx0EShmaQjcHa6AXiOv6qHQu9lCAIR8O+/D8FtaCoJ2c0Tf9Xo7hYH01Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/autoloader/prism-autoloader.min.js" integrity="sha512-SkmBfuA2hqjzEVpmnMt/LINrjop3GKWqsuLSSB3e7iBmYK7JuWw4ldmmxwD9mdm2IRTTi0OxSAfEGvgEi0i2Kw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
- Hit Save and you're done!
Copy to clipboard
If you want to also add a Copy button, which I highly recommend for user convenience, the steps are identical.
In addition to the previous code, add the following code below the ones you added:
Using themes
Prism has a set of themes available to install. Here in this guide we've installed the default theme, which looks quite fine and is used in this site. However, if you want to use a theme, here's how.
To preview themes, go to PrismJS's site and on the right you can select any theme and see the theme in the examples. If you want to switch to a different theme, you have to simply replace the code block that imports the theme from Site heading. In this guide's case, it's the one with /1.29.0/themes/prism.min.css
inside.
To get the code block of your chosen theme, go to their cdn page, select your version (this guide uses 1.29.0, the latest as of now), and search for the theme name. For example, I liked the Solarized Light theme, so I found this cdn script:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-solarizedlight.min.css" integrity="sha512-fibfhB71IpdEKqLKXP/96WuX1cTMmvZioYp7T6I+lTbvJrrjEGeyYdAf09GHpFptF8toQ32woGZ8bw9+HjZc0A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
Replace the default theme with your new theme in the Code Injection page, and you're done!
Conclusion
That's it! You now have both code-highlighting and copying to clipboard. And you also know how to use a predefined theme!