Dynamically Rendering GitHub Files in Web Pages - No Fluff Just Stuff

Dynamically Rendering GitHub Files in Web Pages

Posted by: James Ward on June 15, 2012

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.

James Ward

About James Ward

Professional software developer since 1997, with much of that time spent helping developers build software that doesn't suck. A Typed Pure Functional Programming zealot who often compromises on his ideals to just get stuff done. Currently a Developer Advocate for AWS and AAIF Technical Committee member.

Why Attend the NFJS Tour?

  • » Cutting-Edge Technologies
  • » Agile Practices
  • » Peer Exchange

Current Topics:

  • Languages on the JVM: Scala, Groovy, Clojure
  • Enterprise Java
  • Core Java, Java 8
  • Agility
  • Testing: Geb, Spock, Easyb
  • REST
  • NoSQL: MongoDB, Cassandra
  • Hadoop
  • Spring 4
  • Cloud
  • Automation Tools: Gradle, Git, Jenkins, Sonar
  • HTML5, CSS3, AngularJS, jQuery, Usability
  • Mobile Apps - iPhone and Android
  • More...
Learn More »