Syntax Highlightighting using Prism

Writin a blog about coding, its useful to be able to display code in a readable way.

With HTML we can use the <pre> tag for preformatting things, but it doesn’t do syntax highlighting. I had a look around at other code blogs did a few searches and found Prism.

You need to download a CSS file and a JavaScript library. I would have preferred pure CSS, but I am not even sure if that is possible without adding a lot of classes to the HTML. It took me less than 20 minutes to get it working, so that’s pretty good in terms of ease of use.

Download Prism libraries.

This was about the only part that caused me a problem. The original example I was looking at had Prism highlighting HTML, and CSS code and was served from a CDN. I copied the CDN location and added it to my own HTML, and it formatted the code nicely, but didn’t do the syntax highlighting that I was looking for.

Then looking at the Prism website, there are a large number of languages with checkboxes beside them. The python checbox wasn’t ticked.

Prism download page

So it turns out that you need to specify the languages you want to use and download a custom copy of Prsim (unless you are using the default languages). It also gives you an option to choose a different theme, so I went for a dark background.

Anyway, I added Python and a couple of other languages and downloaded my custom copy.

Update your HTML

I added the Prism js and CSS files to the head of my HTML.


<link rel="stylesheet" href="/css/prism.css">
<script src="/js/prism.js"></script>

Then its a case of wrapping the code in two tags, pre and code. The class on the code tag should be whatever language yoyu need to highlight - in my case python.


<pre>
<code class="language-python">
from django.contrib.auth.hashers import check_password
..
.
</code>
</pre>


escaping HTML

One thing worth noting (as I discovered writing this post) is that code for HTML (and I assume for JS and CSS) needs to be escaped, otherwise the broswer will try to render it.

I used this site, cutting and pasting the small piece of example code that you see above to get this, which went into the file for creating this blog post.


&lt;pre&gt;
&lt;code class=&quot;language-python&quot;&gt;
from django.contrib.auth.hashers import check_password
..
.
&lt;/code&gt;
&lt;/pre&gt;

Written on February 19, 2017