Using Github as a Syntax Highlighter for Your Blog or Website
Gist is a simple way to share snippets and pastes with others. All gists are git repositories, so they are automatically versioned, forkable and usable as a git repository.
A Gist is a snippet of code hosted by Github that has all of the benefits of a Github repository, but provides them to you in a more lightweight way. Not only are public Gists free to create and store on Github they are also super easy. You can create a new Gist, add, modify, and delete files and code entirely in the browser. You don't need to install or download anything.
As developers, bloggers, and/or website owners we can create Gists that contain example code and embed them on our site. By doing this, we get the huge benefit of having all of our source code hosted and backed up separate from your website. Your Gists are also indexed by Google using Githubs Google Juice (better Page Ranking) and you also get to leverage part of the fantastic infrastructure that Github has.
Letting Github host and display your code in a clean and maintainable way is easy, just follow these simple steps:
Step 1: Create a Gist
- Log in to Github
- Click the Gist link at the top of the screen (or go to gist.github.com)
- Fill out the file name (description is optional)
- Enter your code
- Click Create Public Gist
- Optional: You can also click Add File at the bottom to split your code snippet up into several different files if you need to.
Note: The syntax highlighting is auto-detected based on the extension of the file name that you enter, so be sure you add the appropriate level of detail.
Step 2: Embed your Gist
Once you create your Gist, you will be presented with a confirmation page. Click the show embed link and copy/paste the script tag on to your website.
Now, when your page is loaded, your code will be pulled in from Github and automatically formatted.
Step 3: Show RSS readers some love
This step is important if you have users that consume your site's content outside of the site itself such as RSS readers. This will also come in handy for those who disable JavaScript, but I have still yet to meet one of those people in my decade of development experience. If you're out there, please send me an email so I know you exist. Regardless, if you have a blog, chances are someone will benefit from this, so be sure not to leave them out.
Keep in mind that you need to properly escape your HTML special characters, or your RSS applications will think you are using an actual tag. For a working example, Right-click and hit view source to see what I did for this post.
Done!
And, that's it. May your code outlive your blog.
Subscribe for Free
Want to stay ahead of the curve? Subscribe now to receive the latest updates, actionable insights, and thought-provoking ideas around business, technology, and leadership straight to your inbox.