Ghost Theme Customization Part 3: Upgrading Code Blocks with Prism.js Plugins
Adding line numbers and a copy button to Ghost blog code blocks with Prism.js plugins — a step-by-step guide even development beginners can follow, plus stories of trial and error.
In the last part I applied syntax highlighting to the Ghost theme with Prism.js, but once I actually used it, something felt missing. Looking at other development blogs, they had line numbers next to the code and a copy button too. Wondering "Could I build something like that?", I started another friendly conversation with Claude AI.
Fortunately, I learned that Prism.js has plugins that make it easy to add these features. Here's the process I learned through trial and error.
Which Plugins Should I Add?
Searching around, there were really a lot of plugins. I picked the practical, widely used ones:
- Line Numbers: shows code line numbers
- Copy to Clipboard: adds a copy button
- Line Highlight: highlights specific lines
- Show Language: shows the code language
I was tempted to add them all, but decided to start with the most needed: line numbers and a copy button.
Method 1: Add Them Simply via CDN
If you used the CDN method in the previous part, you can easily add the plugins via CDN too.
Ghost Admin → Settings → Code injection → add to Site Footer:
<!-- Add below the existing Prism.js scripts -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/copy-to-clipboard/prism-copy-to-clipboard.min.js"></script>Add the CSS to Site Header:
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/plugins/line-numbers/prism-line-numbers.min.css">But since I downloaded and customized the files myself in the previous part, I'll proceed the same way this time.
Method 2: Download the Files and Apply Them Yourself
Step 1: Download the Plugin Files
On the Prism.js download page, this time select the plugins as well.
Plugins to select:
- ✅ Line Numbers
- ✅ Copy to Clipboard Button
- ✅ Show Language (added as a bonus)
💡 A trial-and-error story: at first I tried to download just the plugins separately, but the dependencies got tangled. It's easier to just download everything again from scratch.
Step 2: Prepare the Dev Environment
Tweak gulpfile.js a little: modify the line that merges main.js and prism.js at build time.
Open ~/ghost-dev/content/themes/ruby/gulpfile.js and change the following:
# Before
jsFiles.push(src(`assets/js/main.js`));
# After
jsFiles.push(src(`assets/js/*.js`));Start the dev server.
cd ~/ghost-dev/content/themes/ruby
yarn devStep 3: Update the CSS File
Replace the existing file with the newly downloaded prism.css, which also includes the plugin styles.
Replace assets/css/misc/prism.css with the new file, and add back the JetBrains Mono font settings from before:
/* Code block font */
code[class*="language-"],
pre[class*="language-"] {
font-family: "JetBrains Mono", Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
font-size: 0.9em;
}
/* Customize line number styles */
.line-numbers .line-numbers-rows {
border-right: 1px solid #999;
padding-right: 0.8em;
margin-right: 0.8em;
}
/* Copy button styles */
.copy-to-clipboard-button {
position: absolute;
top: 0.5em;
right: 0.5em;
padding: 0.25em 0.5em;
background: #f5f2f0;
border: 1px solid #ccc;
border-radius: 3px;
cursor: pointer;
font-size: 0.8em;
}
.copy-to-clipboard-button:hover {
background: #e6e3e0;
}Step 4: Update the JavaScript File
Update with the contents of the newly downloaded prism.js.
Step 5: Add the HTML Class Setup
To use line numbers, code blocks need a special class. In Ghost, you need a setup that adds it automatically.
Add the following code to assets/js/main.js.
In the last post I pasted the prism.js contents into main.js, but this time I'm putting only the needed code into the original main.js and changing the setup so that prism.js is merged by the gulp file.
# Original main.js
(function () {
pagination(true);
})();# Add the following to main.js
// Prism feature setup
function setupPrismFeatures() {
// Handle every code block (including those generated from Markdown)
const allCodeBlocks = document.querySelectorAll('pre code, pre[class*="language-"]');
allCodeBlocks.forEach(function(element) {
let block = element.tagName === 'PRE' ? element : element.parentElement;
// Handle the language class
let className = element.className || block.className;
const languageMatch = className.match(/(?:language-|lang-)(\w+)(?:\{[\d,-]+\})?/);
if (languageMatch) {
const language = languageMatch[1];
block.className = 'language-' + language + ' line-numbers';
element.className = 'language-' + language;
block.setAttribute('data-language', language.toUpperCase());
// Handle line-highlight syntax {2,4-6}
const highlightMatch = className.match(/\{([\d,-]+)\}/);
if (highlightMatch) {
block.setAttribute('data-line', highlightMatch[1]);
}
} else {
// Default code block
block.classList.add('line-numbers');
}
});
}
// Set copy button labels
function setupCopyButtons() {
const copyButtons = document.querySelectorAll('.copy-to-clipboard-button');
copyButtons.forEach(function(button) {
button.textContent = 'Copy';
button.addEventListener('click', function() {
this.textContent = 'Copied!';
setTimeout(() => {
this.textContent = 'Copy';
}, 2000);
});
});
}
// Run after the DOM loads
document.addEventListener('DOMContentLoaded', function() {
// Wait for Prism to load, then run
const waitForPrism = setInterval(function() {
if (typeof Prism !== 'undefined') {
clearInterval(waitForPrism);
setupPrismFeatures();
Prism.highlightAll();
setTimeout(setupCopyButtons, 300);
}
}, 50);
});🤔 Why is this code needed? Ghost's Markdown parser doesn't add the line-numbers class automatically, so you have to add it with JavaScript. There was also a problem merging with Prism.js and it didn't apply: Prism.js has to load first, but the code was running right after the DOM loaded, before Prism.js had initialized — Claude AI explained this, and I finished the code above with its help.Step 6: Build and Apply the Theme
# Stop the dev server
Ctrl + C
# Package the theme
yarn zipHow Is It in Actual Use?
Line Numbers
Really useful when code gets long. Especially when an error message says "there's a problem on line 15," you can find it right away.
Copy Button
It's really convenient for readers copying code. No more accidentally copying the line numbers when dragging with the mouse.
Language Label
With the language shown at the top right of the code block, you can tell what it is at a glance.
Extra Customization Tips
Highlighting Specific Lines
When writing a code block in the Ghost editor, you can highlight specific lines like this:
```javascript{2,4-6}const message = "Hello World";
console.log(message); // this line is highlighted
const number = 42;
const array = [1, 2, 3]; // from this line
const object = {}; // through here
const result = true; // highlighted up to hereWhat I Learned Through Trial and Error
- Plugin dependencies: plugins depend on each other, so they need to load in order
- Adding classes automatically: Ghost doesn't add classes automatically, so you have to do it with JavaScript
- CSS specificity: it can clash with existing theme styles, so adjust CSS specificity carefully
- Mobile support: the copy button may not be very visible on mobile, so make it responsive
Wrapping Up
At first I thought, "Aren't advanced features like this only for developers?" But once I tried, it was easier than expected. Of course I got stuck a few times along the way, but with Claude AI's help and some trial and error, I got it done in the end!
Now my blog's code blocks look much more professional. Line numbers, a copy button, a language label... it actually feels like a real development blog! 😄
Next I'd like to add things like a comment system or search, and I'll learn those step by step and share them too.
If you get stuck while following along, please leave a comment. I'm a beginner too, so it won't be perfect, but it'd be nice to work it out together! 🚀
References: