How To Post Code Snippets On Your Website
If you have been following my blog since my first post, you may notice that I have made some substantial improvements to my site to help bring a better experience to my followers and new visitors. While I could make a blog post dedicated to explaining why I made these changes, I figured it would be boring, and perhaps the information would become out dated as time went on. However, I will write about some of the changes I made that you can implement on your blog or website right now.
One of the very first changes I made was, figuring out a better way to post code snippets on my website. This task is very important to me for two reasons. First, I like to share code whenever possible. I find sharing code is very useful especially when writing a tutorial like this one. It helps give the user a quick look inside your favorite programming language and coding style. In addition, it also helps make your content more interactive. Second, the method I had in place for posting code was not working anymore and did not support all browsers.
Previous to these changes, I use to use the code tag in the body of my posts, in order to tell WordPress that the text inside the tag was source code. This worked for one post. As I found out later, this method did not work for longer snippets that contained multiple lines. In those cases, the code tag would handle the first line of code fine. But failed to handle any of the other lines. This failure also destroyed any indentations that were created from the code editor. In addition one of my followers pointed out that the code did not render right across browsers. As you can see, this presents a problem, and I needed a solution fast.
My first attempt to fix this was redoing the code tags. This sometimes worked but did not fix the browser issue. Next, I tried a bunch of WordPress plugins. I found a couple that were free and that I liked. However, the purpose of these plugins were to run custom code inside WordPress. Since these plugins did not fit my use case and I did not use them. In case you are interested, I tried the following plugins:
After not having any luck, I remembered that I could embed a GitHub Gist into my posts. This is the best solution because it does not require plugins, and GitHub’s editor could keep the source formatting. I tried this out on my post about VB.Net. To my surprise, it worked better than expected. It made everything more readable and preserved the formatting. Plus it seemed to work across browsers too. I also applied this method to the code I posted in my last post about Threading in iOS Applications. Problem solved. I recommend this solution to any developer that wants to blog about the code they are writing.