How to Embed Raw Code From Github Into a Ghost Post | Zuar
Embed Github raw code into a Ghost post. This is an integration-free solution, using only HTML and Javascript.
Mục Lục
No integrations needed: Use only HTML and Javascript
Internally we’re using the Ghost blogging platform for our customer documentation, as well as the blog you’re reading now. Often that includes coding examples, and snippets of JSON. Many times the code we’re sharing is already stored in a public git repo, and over time those examples drift to keep up with versioning.
When looking for options to embed code snippets from another source the #1 solution is to use gists, which is very convenient, and provides ready made embed code. For our use case, however, the code was already in a public github repo, so using gists isn’t ideal.
We needed a single source of truth. A solution that allowed us to embed directly from a git repo. When the code in git changes, the code in our blog should change too.
Luckily Ghost allows users to create HTML blocks, so a solution wasn’t too difficult to create. Consider the following HTML/JS:
<pre id="show-json-from-git"></pre>
<script>
var url = 'https://raw.githubusercontent.com/{gitAccount}/{publicGitRepo}/{branch}/{filename.json}';
fetch(url)
.then(res => res.text())
.then((out) => {
document.getElementById("show-json-from-git").innerText = out
})
.catch(err => { throw err });
</script>
Usage
From a public git repo web UI, navigate to the file we want to embed, and click on the Raw
button:
github raw button
Copy the raw URL from the browser’s location bar.
Edit and use the HTML block above with the raw URL, then save and preview to see the embedded code.
Troubleshooting
If you do not see your embedded code check the javascript console in your developer tools. You can add console.log
as needed to debug any specific issue.
When using this code to embed more than one snippet on the same post, please note: var url
will require a unique name in every HTML block. So on the second usage you might use var url2
. Same goes for the ID of the <pre>
tag.
Example
The following code block is embedded from https://github.com/zuarbase/mitto-job-templates/blob/master/cmd/bash_scripts/example.sh:
Summary
We hope you found this article helpful! Next, if you want to know more about automatically pulling data from GitHub into a database and preparing it for analysis, check out our Mitto ELT+ product.