Dynamically Rendering GitHub Files in Web Pages
You know how you can easily embed GitHub Gists into a webpage? I’ve always wanted that for any file on GitHub. I post a lot of code on my blog and it’s always tedious and error-prone having to copy and paste the code. I’d rather be able to dynamically render a specific version of a file hosted on GitHub. So I created a little JavaScript jQuery plugin called github-files that pulls blobs from GitHub. Those blobs can then be rendered client-side and optionally syntax highlighted.
To use github-files, get the git sha for a file:git rev-parse HEAD:src/main/javascript/github-files.js
Then you can grab the file from GitHub in JavaScript:
$.getGithubFile("user", "repo", "sha",
function(contents) {
console.log(contents)
}
)
Here’s the source for github-files.js, fetched dynamically using github-files.js and rendered with highlight.js:
```
This uses GitHub’s JSONP API to pull the file in. It’s pretty simple and could use a few more features but it’s a start! Matt Raible and I are using this for our upcoming ÜberConf presentation to render code in our reveal.js preso. Hopefully this is useful for others. Let me know what you think.