Tuesday, January 28, 2014

Daniel That: How to display code in blogger posts

Daniel That: How to display code in blogger posts



How to display code in blogger posts

In this post, I'm going to show step by step how to display code nicely in blogger posts using SyntaxHighlighter.

1) First, we need to add the html code below on the head section of our blogger template. To do this, inside blogger:
  • Select Template on the left hand side.
  • Click Edit HTML.
  • Then copy the code below just before the closing head tag (i.e </head>). You can easily find it by using the search box accessing to it with Control+F.

<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/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushJava.js' type='text/javascript'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shBrushXml.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
SyntaxHighlighter.config.bloggerMode = true;
SyntaxHighlighter.all();
</script>

On line 4 and 5 (violet color), I'm loading the syntax template for Java code and XML code, but there are much more like PHP, Perl, SQL,... you can find the complete list here.


2) Now that the blogger template is ready, we need to prepare the code to ensure correct rendering. Basically, we need to HTML escape some characters like right angle brackets, e.g. all < must be replaced with &lt;. To do so, you can use one of the following online tools:

http://www.accessify.com/tools-and-wizards/developer-tools/quick-escape/default.php


3) Once you have the code with escaped characters, you can copy it on your blogger post inside <pre> tags. In the title you can choose a title for the code block and in the class you choose the code template to use.

<pre title="here goes a title" class="brush:xml;">
...
</pre>


4) And that's it, here is an example:
html code using SyntaxHighlight
1
2
3
4
5
6
7
8
9
<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/shThemeEclipse.css' rel='stylesheet' type='text/css'/>
<script src='http://alexgorbatchev.com/pub/sh/current/scripts/shCore.js' type='text/javascript'/>
<script language='javascript' type='text/javascript'>
    SyntaxHighlighter.config.bloggerMode = true;
    SyntaxHighlighter.all();
</script>

No comments:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...