Tuesday, October 2, 2012

Code Formatting in Blogger

I've several hours of research, trial, and error, I've finally come across a workable solution for formatting code snippets in Blogger. Here are the basic steps:
  1. From your dashboard view, click "Template" and then "Edit HTML".  A modal confirmation dialog will appear.  Click "Proceed".
  2. Find the <head> tag and insert the following on the next line:
    <link href='https://sites.google.com/site/itswadesh/codehighlighter/shCore.css' rel='stylesheet' type='text/css' />
        <link href='http://sites.google.com/site/itswadesh/codehighlighter/shThemeDefault.css' rel='stylesheet' type='text/css' />
        <script src='http://sites.google.com/site/itswadesh/codehighlighter/shCore.js' type='text/javascript' />
        <script src='http://sites.google.com/site/itswadesh/codehighlighter/shBrushCSharp.js' type='text/javascript' />
        <script src='http://sites.google.com/site/itswadesh/codehighlighter/shBrushJava.js' type='text/javascript' />
        <script src='http://sites.google.com/site/itswadesh/codehighlighter/shBrushCss.js' type='text/javascript' />
        <script src='http://sites.google.com/site/itswadesh/codehighlighter/shBrushXml.js' type='text/javascript' />
        <script type='text/javascript'>
            // Required for Blogger:
            SyntaxHighlighter.config.bloggerMode = true;
            // Set to true to enable line numbers:
            SyntaxHighlighter.defaults['gutter'] = false;
            // Apply formatting:
            SyntaxHighlighter.all();
        </script>
    

  3. Save the template

Once your template is updated, simply wrap your code snippets in a <pre> tag with a special class:

<pre class="brush: csharp">
public class Test
{
    public string Property { get; set; }

    public void Method()
    {
    }
}
</pre>

The result should look something like this:
public class Test
{
    public string Property { get; set; }

    public void Method()
    {
    }
}

The full list of brushes can be found here. Note that the HTML snippet in step 2 above only imports the C#, Java, XML, and CSS brushes. If, for example, you wanted to use Erlang, you would also have to include the following <script> tag:

    <script src='http://sites.google.com/site/itswadesh/codehighlighter/shBrushErlang.js' type='text/javascript' />

No comments:

Post a Comment