How to add line numbers to Prism in Ghost

Ghost Sep 26, 2021

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.

Header

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/plugins/line-numbers/prism-line-numbers.min.css"/>

Footer

<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.25.0/plugins/line-numbers/prism-line-numbers.min.js"></script>

Do not forget to click the Save button.

ghost_dasboard_code_injection

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.

ghost_dashboard_post_editor_html_block

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>

The 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.

ghost_dashboard_test_blog_with_code_block_skipping_line_1
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.

ghost_dashboard_test_blog_with_code_block

3. Using '<'  and '>' in your code block

Now before I end this post, there is one more problem that I have to mention. Using < and > inside of the code block will result in the code not being shown. This can be a problem when for example using <?php or <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: &lt;html&gt; by using the HTML special entities &lt; and &gt; to get the characters < and >. Now you will get your desired output in the code block.

<pre class="line-numbers language-html"><code>
	<html>
</pre></code>

Conclusion

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.

Tags