Wednesday, November 24, 2010

First post: adding code to a post

As a first post, I'd like to add something I ran into when trying to make this blog work: adding code to a post. Of course I would like for it to look nice.

After some searching I found this post by Iain which explains exactly that.

The short of it:
1) Add the following in the head section of your blog.
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shCore.css' rel='stylesheet' type='text/css'/>
<link href='http://alexgorbatchev.com/pub/sh/current/styles/shThemeDefault.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'></script>
<!-- add brushes here -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJScript.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushBash.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushSql.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCpp.js' type='text/javascript'></script>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCSharp.js' type='text/javascript'></script>
<script type='text/javascript'>
  SyntaxHighlighter.config.bloggerMode = true;
  SyntaxHighlighter.all();
</script>
 
2) Add your html-encoded text in the following html tags:
<pre class="brush:csharp">
  ...your code..
</pre>
Here is an example of the result:
using System;

namespace Demo {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Hello world!");
        }
    }
}
It works for all kinds of languages, and also for C#. Just what I needed :-)

Kudos to Alex Gorbatchev for creating this wonderful piece of javascript, and to Iain for letting me find it.