How to display code in Blogger blog

So, you want to display some code in your blog, eh? Once you know how to do it, it is pretty easy, but it can be tricky at first.

First things first: Switch to "Edit HTML" mode in the post editor. It will make this process much easier. You can switch between the two using the tabs above the post editor:


Important! Before trying to display any HTML code, be sure to sanitize!

Sanitizing HTML code replaces angle brackets (> , <) with the escaped version of the character. This way, Blogger and your viewer's browsers won't try to interpret and render the code as HTML - they will instead display it literally as text. I use the simple tool here whenever I need to post HTML code.

There are several ways to approach this. I prefer to use a pre tag around a code block in all cases, but each had advantages and different prep. The main advantage of using a pre tag is that it degrades nicely for RSS readers.

Plain Pre

This will remove any formatting from the text, generally applying a monospace font, such as Courier New. It's simple and easy, and preserves tabs and spacing [excluding text wrap]. The downside is that it's just plain text, with no line numbers, highlighting or styling. (Being a simple tag, you can of course style pre using CSS, but by default it strips styling)

You would use it like this:
<pre>
CODE 
</pre>

And it would produce something like this (Sample code from wiki):

/**
     * Constructor: an ID# and two shared resources
     * @param i
     * @param fork1
     * @param fork2
     */
    public Philosopher(int i, Semaphore fork1, Semaphore fork2)
    {
        id = i;
        myFork = fork1;
        myNeighborsFork = fork2;
    }
(image)

Some people suggest the <code> tag

But I personally don't like it. Pre preserves formatting and spacing, while code does not. For example, the following code is inside a <code> block. You'll notice how, compared to the same code above, it has lost all indentation.

/**
* Constructor: an ID# and two shared resources
* @param i
* @param fork1
* @param fork2
*/
public Philosopher(int i, Semaphore fork1, Semaphore fork2)
{
id = i;
myFork = fork1;
myNeighborsFork = fork2;
}
(image)

Styled Pre

The second approach is to define your own styling for code blocks. This can make your code blocks stand out more or look prettier. If you want to style your code blocks, it is best to create a CSS class for use with a tag, for example pre, instead of styling all instances of the tag. This way you can use the default function of the tag, as well as the styled versions. The styling would be entirely up to you. I'll make an example.

The style definition would go in your blog template. You can do this by either directly modifying your template in Design -> "Edit HTML" and insert the CSS anywhere between the <head> and </head> tags. Or, you can use the template designer. Design -> Template Designer -> Advanced, and insert it in the box labelled "Add custom CSS".

Example code for template:
<style>
.stylecode {
display:block;
background-color:#F7E7A3;
color:#33312B;
border:3px solid #F0B326;
}
</style>

And it would be used like this in a post:
<pre class="stylecode">
CODE
</pre>

And this particular sample would look like this:
/**
     * Constructor: an ID# and two shared resources
     * @param i
     * @param fork1
     * @param fork2
     */
    public Philosopher(int i, Semaphore fork1, Semaphore fork2)
    {
        id = i;
        myFork = fork1;
        myNeighborsFork = fork2;
    }
(image)
Since it's just CSS, you could apply any styling you can think of - colours, fonts, borders, images, etc. If you define the styling in your template, it won't show up in RSS readers, since the feed only publishes the content of a post - not the blog template styling. Instead, your styled code block will gracefully degrade into a plain pre block. If you wanted the styling to remain in your posts, you would have to include the CSS style definition in every post so the RSS reader would know it's there.
As an example of the sorts of neat things you can do with CSS, you can limit the vertical or horizontal size of the code block.
<style>
.scrollCode {
display:block;
height:100px;
overflow:auto;
border:1px solid black; /* optional; just for better visual*/
}
</style>
Which can be used like,
<pre class="scrollCode">
CODE
</pre>

and will produce a result like,
/**
     * Constructor: an ID# and two shared resources
     * @param i
     * @param fork1
     * @param fork2
     */
    public Philosopher(int i, Semaphore fork1, Semaphore fork2) /* adding a very long comment here to force demonstration of a horizontal scrollbar*/
    {
        id = i;
        myFork = fork1;
        myNeighborsFork = fork2;
    }
(image)

SyntaxHighlighter Script

For many people, that simply isn't enough. We want syntax highlighting. We want line numbers. For this case, you will generally have to use javascript to apply styling to keywords, and allow line numbering. I employ SytaxHighlighter on my blog, and have has great success with it. (example image)

SyntaxHighlighter is a script written by a fellow named Alex Gorbatchev to make code highlighting and display visually appealing and easy to read. The thing that makes it ideal for Blogger blogs is that he hosts the script source for you - because generally bloggers on Blogspot don't have their own webspace to host things from. (If you do have hosting space available, I would encourage you to host them yourself!)

It works easily enough if you use the pre method. After including all the necessary files (see below), you use it by putting your code between pre tags assigned a class of a specific "brush". You must specify the brush for highlighting - that is, you have to tell the script what language is being highlighted, so it knows what keywords to colour. For example, to use the CSS brush, you would do:

<pre class="brush:css">
CODE
</pre>

SyntaxHighlighter "installs" easily in a blog. Just insert the code to link to the script source into the beginning of the template, before the <head> tag. You can, by default include all the "brushes" or, to improve the speed of your webpage, only include the brushes you plan to use.

(Some full instructions targeted specifically at Blogger blogs here)

My template looks something like this, with a few brushes cut out for brevity:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html expr:dir='data:blog.languageDirection' xmlns='http://www.w3.org/1999/xhtml' xmlns:b='http://www.google.com/2005/gml/b' xmlns:data='http://www.google.com/2005/gml/data' xmlns:expr='http://www.google.com/2005/gml/expr'>

<!--Syntax Highlighter -->
<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'/>

<!--Syntax Highlighter Brushes -->
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushCss.js' type='text/javascript'/>

<script language='javascript'> 
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.config.clipboardSwf = 'http://alexgorbatchev.com/pub/sh/current/scripts/clipboard.swf'
SyntaxHighlighter.all();
</script>
<!-- End Syntax Highlighter-->
<head>

    <b:include data='blog' name='all-head-content'/>
    <title><data:blog.pageTitle/></title>
    <b:skin><![CDATA[/*
-----------------------------------------------
Blogger Template Style


SyntaxHighlighter also allows other coloration themes (For dark blogs, or to mimic your favourite editor, for example), and there are many other brushes in addition to the original ones, however you would need to host the javascript files for non-default additional brushes yourself.

The downsides to such a script are obvious: It's an additional script that needs to be run, and can thus make page loading slow. There's a bit of time between when the text loads and when it gets styled. It requires a lot more effort than other approaches. The styling won't show up in an RSS reader, but at least the code degrades to a plain, unstyled pre block, so it's not that bad.

However, I prefer this method to any other because it allows line numbers, it doesn't wrap text, it's easy to copy and paste code without formatting errors (Some other code block implementations with line numbers I have encountered create annoying formatting problems), and syntax highlighting is essential for making long pieces of code readable.

5 things about

How to display code in Blogger blog
  1. pre tag doesn't work :(

    ReplyDelete
  2. Thank you for you post. I used your suggestion and it works great, check it out: http://pc-technic.blogspot.com/2011/04/php-dynamic-stored-procedure.html

    ReplyDelete
  3. Anon: I don't know why you'd be having trouble; it's a standard tag supported by all browsers. :(

    Ultimatum: I;m glad you found it useful!

    ReplyDelete
  4. extremely cool. Thanks for the info. I'll use it on my "Learning C++" ongoing saga.

    ReplyDelete
  5. Well, since HTML, and HTML5 in particular, is a _semantic_ markup language you should use the code element for code. Thats what it is for. If you want to give it the pre behavior it is simply possible with CSS:

    code { white-space: pre; }

    ReplyDelete

Copyright 2012 Phile not Found. See About
Powered by Blogger

"Whenever you find that you are on the side of the majority, it is time to pause and reflect."