Generate GitHub Pages from your project’s readme.md

Using a project’s readme.md to generate a GitHub page is surprisingly easy. Why write content twice?

Prerequisites

For this to work you’ll need jQuery and a Markdown parser. I used pagedown because it’s really simple to use and supports almost everything I need. I’m now recommending Parsedown because it’s epic-fast and supports Github Flavored Markdown.

Creating the Template

Create index.html and code a basic HTML template:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>GitHub Page Template</title>
        <!-- Stylesheets, etc. -->
    </head>
    <body>
        <div class="wrapper">
            <img src="spinner.gif">
        </div>
        <script src="jquery-1.11.1.min.js"></script>
        <script src="Markdown.Converter.js"></script>
        <script src="script.js"></script>
    </body>
</html>

Getting readme.md content

You can’t just get files from “https://raw.githubusercontent.com” because they’ll have the wrong content headers, so paste the link to your raw readme.md into RawGIt and use the URL it generates.

As it says on RawGIt, the “Production” URL it generates gets cached permanenelty, but has the advantage of using a CDN. Therefore you have two options:

  1. Use the “Development” URL for the readme from the master branch
  2. Use the “Production” URL for the readme from a specific tag or commit

I’ll let you weigh the relative merits of each, suffice it to say that I used the “Development” URL for the readme from the master branch. That way, when merged, the GitHub Page will automatically update with the new readme.

How to get readme.md

Put the following in your script file and add your readme.md URL:

// Choose branch based on query string
var query = window.location.search;
if (query) {
    var branch = query.replace("?", "");
} else {
    var branch = "master";
}

// Load readme content
$.ajax({
    url: "https://rawgit.com/richjenks/teepee/"+branch+"/readme.md",
    dataType: 'text',
    success: function(data) {

        // Convert readme from markdown to html
        var converter = new Markdown.Converter();

        // Show html
        $(".wrapper").html(converter.makeHtml(data));

    }
});

Deployment

To deploy, follow the steps at https://help.github.com/articles/creating-project-pages-manually.

How it works

RawGit generates a URL to your readme.md file on GitHub with correct content headers, which you put in an ajax call. When index.html first loads, it shows a spinner gif so the user isn’t presented with a blank screen and when the ajax call returns, its callback runs the response through the Markdown parser.

Then it puts the HTML in-place of the spinner—simple really!

Leave a Reply

Your email address will not be published.