In this post, I will show you how to add line numbers within your Prism Syntax Highlighters. I will also show you the solutions to common problems people run into when using Prism line numbers.
1. Inject line number CDNs
First, we start by adding the line-numbers CDNs within our Code Injection.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/plugins/line-numbers/prism-line-numbers.min.css"/>
Do not forget to click the Save button.
2. Create the code block
Since we have added the CDN's you can navigate to your posts editor, and create a new HTML card.
Normally we create a code block by typing 3 backticks
(```) and pressing tab. But because we want line numbers we have to do this differently. Inside your HTML card, you paste the following code.
<pre class="line-numbers language-python"><code> // Your code </pre></code>
language-python class determines which language you are using, change this accordingly.
After you did this you can click on Preview and you will see the following result.
I pasted in some Python code for demonstration purposes, the code is not shown in the example code blocks.
As you can see we have the line numbers now, but there is still one problem, line 1 is getting skipped, but we can easily fix this. Put the first line of your code on the same line as the HTML as shown below.
<pre class="line-numbers language-python"><code>// First code line </pre></code>
If you did it correctly your code will start from line 1.
3. Using '<' and '>' in your code block
Now before I end this post, there is one more problem that I have to mention. Using
> inside of the code block will result in the code not being shown. This can be a problem when for example using
<html> tags. In the code block below I put
<html> but as you can see it does not show up.
<pre class="line-numbers language-html"><code> </pre></code>
So to solve this we have to write
<html> like this:
<html> by using the HTML special entities
> to get the characters
>. Now you will get your desired output in the code block.
<pre class="line-numbers language-html"><code> <html> </pre></code>
In this post, we learned how you can add line numbers to your Prism Syntax highlighter. It took me a long time to figure this out, so I am glad I can show you this so you do not have to go through the same struggle as I did.