1: Add the script and css to your page layout
In your Blogger account go to 'Create Post' and then to the 'Layout' tab. You will see the page elements laid out. Click 'Edit Html' in the second row of tabs.
You're going to add two lines at the end of the HEAD section just before the </head> tag. The first one pulls in the CSS file from the repository and the second pulls in the Javascript code.
<link href='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.css'
rel='stylesheet' type='text/css'/>
<script src='http://google-code-prettify.googlecode.com/svn/trunk/src/prettify.js'
type='text/javascript'/>
</head>
If you wanted to avoid the calls out to that site you could just inline the content of those files.
Immediately below the </head> tag, change <body> to:
<body onload='prettyPrint()'>
This loads the JavaScript when the page loads. Save the template and go to 'Posting' -> 'Create' to create a test post.
2: Create a test post
Enter in some text into the new post and then enter a block of code. The prettifier can figure out most languages. For example:
['apple', 'orange', 'banana'].each do |fruit|
puts fruit
end
Go into the 'Edit Html' tab and put <pre> tags around your code. Add the special class as shown:
<pre class='prettyprint'>
['apple', 'orange', 'banana'].each do |fruit|
puts fruit
end
</pre>
Unfortunately syntax highlighting does not work in Preview mode or the Compose window. You just have to bite the bullet and publish your post to see what it looks like. And it should look something like the code blocks in this post.
To represent blocks of HTML code or anything with angle brackets you need to change the brackets to < and >, otherwise Blogger will try and treat them as html tags.
You can help the highlighter out by specifying the specific language to use by adding a second class to the pre tag such as:
<pre class="prettyprint lang-html">
You can check out the prettify JavaScript file to see which languages have specific classes like this. But it does a pretty good job even without that. You can use <pre> or <code> tags this way. The only difference is that the <code> version omits the surrounding box.
This is pretty slick. The approach ought to work with other syntax highlighters. If you try them let me know what you think in the comments. Now I need to go back in time and add this feature to all my old posts.
No comments:
Post a Comment