Using only HTML and Javascript – No integrations

Internally we're using Ghost 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
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.

Gotchas and 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: