GitHub Gists is a popular platform that offers us to save snippets of code and share them via a link as well as embed them in a webpage. But what if we want to embed code directly from a GitHub repository?
I’ve written a script to embed code from a GitHub repository easily in your webpage. I have used the Prism library for syntax highlighting.
The Script #
<pre id="embed-github-pre"><code class="language-cpp line-numbers" id="embed-github-code"></code></pre>
<script>
let gitHubLink = "https://raw.githubusercontent.com/thecoducer/Competitive-Coding/master/LeetCode/two-sum-2.cpp";
getCodeAsRawTextFromGithub().then(data => {
let preProcessedData = preProcessData(data);
document.getElementById("embed-github-code").innerHTML = preProcessedData;
loadScripts(["https://cdn.jsdelivr.net/gh/thecoducer/anything/prism.js"]);
});
async function getCodeAsRawTextFromGithub() {
let response = await fetch(gitHubLink);
let rawText = await response.text();
return rawText;
}
function preProcessData(data) {
data = data.replaceAll("<", "<");
data = data.replaceAll(">", ">");
return data;
}
function loadScripts(scripts) {
for (let i = 0; i < scripts.length; i++) {
this.insertAScriptTagInsideTheHeadTag(scripts[i]);
}
}
function insertAScriptTagInsideTheHeadTag(src) {
let scriptTag = document.createElement('script');
scriptTag.type = "text/javascript";
scriptTag.async = true;
scriptTag.src = src;
let headTag = document.getElementsByTagName('head')[0];
headTag.appendChild(scriptTag);
}
</script>
How it works? #
The value of gitHubLink
should be the raw URL of the code file on GitHub that you want to embed.
You can find it here
It should look like this: https://raw.githubusercontent.com/<github username>/<repo name>/<branch name>/<dir name>/<filename>.<filename extension>
The JavaScript code hits the URL using the Fetch API and gets the raw text from it. As soon as we receive the response, we do some preprocessing and insert the raw code text inside the HTML code tag, and then we start loading the JS scripts into the DOM. The Prism JS takes the raw text and prettifies it.
There is a caveat here. Prism JS reads any text that is enclosed within angle brackets as an HTML tag. This creates an issue in programming languages where we write certain keywords within angle brackets like C or C++ preprocessor directives or vector<int>
in C++. It ignores the text inside the brackets. Thus, I have handled this corner case inside the preProcessData()
.
How to Use it in WordPress? #
You need to add the Prism CSS file to your WordPress site. Insert the below tag within the head tag or paste it in the headers if you’re using the Insert Headers and Footers plugin in WordPress.
Now, create a new post and add a Custom HTML block. Paste the entire script there.
The language-*
class name added to the code tag should be suffixed with an appropriate name of the programming language that matches your code file. In my case, I’ve used a raw URL for a C++ code file so I’ve added the language-cpp
class to my code tag.
You can check the list of the supported languages and their appropriate class name here.
You need to also change the background color of our pre tag to avoid any CSS styling conflicts. So, insert the below CSS code in your WordPress site.
#embed-github-pre {
background: #2f2f2f;
}
I’m using the Tomorrow Night theme in Prism. So I’ve set the background color value the same as the theme’s value.
Save and Preview the post and you’ll get to see the GitHub repository code got beautifully embedded on your post.
Prism Configurations #
Go through the Prism website and understand how it works. I have customized the Prism files according to my needs and uploaded the minified static files to one of my GitHub repo. And, have used the jsDelivr CDN service to serve the static files. You can have your own customizations. Download and use them instead of my JS and CSS files.