Syntax Highlighting with Prism.js

Shaphil Mahmud
5 min readApr 2, 2020

Add syntax highlighting to your Ghost blog with Prism.js

There is now an official blog post on how to do this. You can find that post here — https://ghost.org/tutorials/code-syntax-highlighting/

TL;DR

  1. Head over to the prism.js CDN — https://cdnjs.com/libraries/prism
  2. Copy required CSS “Link tag”s
  3. Navigate to your site admin > Code Injection
  4. Paste the CSS Link Tag into the Site Header text box
  5. Copy the required JavaScript Script Tags from the prism.js CDN
  6. Paste them into the Site Footer text box

Unfortunately simply copying the link for prism.min.js will not work for all languages. Some languages will need the js file intended for them for the syntax highlighting to work in addition to prism.min.js. For example, I had to add the prism-python.min.js file for the syntax highlighting to work on a block of Python code.

I have added plenty of these js files. Here are some examples,

git config --global user.name "Your Name Comes Here" git config --global user.email [email protected]

<!-- HTML -->
<article class="post-item">
<h2 class="post-title"><a href="/welcome/">Welcome to Ghost</a></h2>
<p>Welcome, it's great to have you here...</p>
<a class="read-more" href="/welcome/">Read more</a>
</article>
# Bash
##########################################################################################
################################## User Settings #####################################
##########################################################################################

alias python=python3
alias pip=pip3
alias venv="virtualenv env"
alias activate="source env/bin/activate"
alias vact="venv && activate"

# git pull all subdirectories
# Source - https://dev.to/rmpato/git-pull-multiple-repositories-at-once-4l68
alias pullall="find . -mindepth 1 -maxdepth 1 -type d -print -exec git -C {} pull \;"

# For NodeJS manually installed from tarball
# Instructions - https://github.com/nodejs/help/wiki/Installation
NODE_VERSION=v12.16.1
NODE_DISTRO=linux-x64

export PATH=/usr/local/lib/nodejs/node-$NODE_VERSION-$NODE_DISTRO/bin/:$PATH

# For Virtualenv installed trough pip
export PATH="~/.local/bin:$PATH"

# Go Lang
# export PATH=$PATH:/usr/local/go/bin
# export PATH=$PATH:~/go/bin

parse_git_branch() {
git branch 2>/dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}

export PS1='${debian_chroot:+($debian_chroot)}\[\033[01;31m\]\u\[\033[01;39m\]@\[\033[01;32m\]\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[01;33m\]$(parse_git_branch)\[\033[00m\]\$ '
// C Programming Language
#include <stdio.h>


int main()
{
const char *str = "can't modify this one";
char *const var = "you can modify this string";

str = "asdasda";

printf("%s\n", str);

return 0;
}
/* C++ */
#include <iostream>

using namespace std;

void pascals_traiangle(int n)
{
int row = n;
int col = 2 * row + 1;
int triangle[row][col];

}

int main()
{

return 0;
}
/* C# */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace code
{
class Program
{
public static void Main(string[] args)
{
sbyte b = 127;
Console.WriteLine(b);
}
}
}
/* CSS */
body {
background-color: lightblue;
}

h1 {
color: white;
text-align: center;
}

p {
font-family: verdana;
font-size: 20px;
}
<!-- Django Template Language -->
{% extends "base_generic.html" %}

{% block title %}{{ section.title }}{% endblock %}

{% block content %}
<h1>{{ section.title }}</h1>

{% for story in story_list %}
<h2>
<a href="{{ story.get_absolute_url }}">
{{ story.headline|upper }}
</a>
</h2>
<p>{{ story.tease|truncatewords:"100" }}</p>
{% endfor %}
{% endblock %}
<!-- Jinja2 -->
<!DOCTYPE html>
<html lang="en">
<head>
<title>My Webpage</title>
</head>
<body>
<ul id="navigation">
{% for item in navigation %}
<li><a href="{{ item.href }}">{{ item.caption }}</a></li>
{% endfor %}
</ul>

<h1>My Webpage</h1>
{{ a_variable }}

{# a comment #}
</body>
</html>
# Dockerfile (yaml)

FROM python:3

# set a directory for the app
WORKDIR /usr/src/app

# copy all the files to the container
COPY . .

# install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# define the port number the container should expose
EXPOSE 5000

# run the command
CMD ["python", "./app.py"]
git config --global user.name "Your Name Comes Here"
git config --global user.email you@yourdomain.example.com
// GoLang
package main

import (
"fmt"
"math"
)

func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// can't use v here, though
return lim
}

func main() {
fmt.Println(
pow(3, 2, 10),
pow(3, 3, 20),
)
}
# GraphQL
{
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}

fragment comparisonFields on Character {
name
appearsIn
friends {
name
}
}
/* Java */

public class ComplexNumber{
// for real and imaginary parts of complex numbers
double real, img;

// constructor to initialize the complex number
ComplexNumber(double r, double i){
this.real = r;
this.img = i;
}

public static ComplexNumber sum(ComplexNumber c1, ComplexNumber c2)
{
// creating a temporary complex number to hold the sum of two numbers
ComplexNumber temp = new ComplexNumber(0, 0);

temp.real = c1.real + c2.real;
temp.img = c1.img + c2.img;

// returning the output complex number
return temp;
}
public static void main(String args[]) {
ComplexNumber c1 = new ComplexNumber(5.5, 4);
ComplexNumber c2 = new ComplexNumber(1.2, 3.5);
ComplexNumber temp = sum(c1, c2);
System.out.printf("Sum is: "+ temp.real+" + "+ temp.img +"i");
}
}
//JavaScript

class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {
constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

mycar = new Model("Ford", "Mustang");
document.getElementById("demo").innerHTML = mycar.show();
// JSON

{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}
## Markdown Tables

| Option | Description |
| ------ | ----------- |
| data | path to data files to supply the data that will be passed into templates. |
| engine | engine to be used for processing templates. Handlebars is the default. |
| ext | extension to be used for dest files. |
# Python program to check if year is a leap year or not

year = 2000

# To get year (integer input) from the user
# year = int(input("Enter a year: "))

if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
--SQL

CREATE TABLE Persons (
ID int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (ID)
);
// TypeScript

class Student {
fullName: string;
constructor(public firstName: string, public middleInitial: string, public lastName: string) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}

interface Person {
firstName: string;
lastName: string;
}

function greeter(person: Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}

let user = new Student("Jane", "M.", "User");

document.body.textContent = greeter(user);
# YAML

doe: "a deer, a female deer"
ray: "a drop of golden sun"
pi: 3.14159
xmas: true
french-hens: 3
calling-birds:
- huey
- dewey
- louie
- fred
xmas-fifth-day:
calling-birds: four
french-hens: 3
golden-rings: 5
partridges:
count: 1
location: "a pear tree"
turtle-doves: two

Originally published at https://blog.shaphil.me on April 2, 2020.

--

--

Shaphil Mahmud

Fullstack Software Engineer. Lover of the backend. Friends with the Frontend. https://shaphil.me