Showing code blocks on your blog

  • Gérald Barré

As editors of technical articles, we often have to submit code on blogs. In this post, I will show you the solution we have chosen for this.

Our need is as follows:

  • The code must not be colored in the source: The code will be formatted automatically when rendering. This allows to harmonize the code throughout the blog and to change the style globally if we wish
  • The code must be easily editable into the post: We mainly use Windows Live Writer for writing posts. The code must be easily editable in this tool.
  • The code should be displayed correctly on the blog and in the RSS feed (especially in Feedly)

#The formatting of the code

The target HTML to display code is:

<pre><code class="language-csharp">public void Sample() { }</code></pre>

This format is the one defined in the HTML5 spec and is used by many editing and formatting tools such as CommonMark.

To format this HTML in the browser, we chose Prismjs because it is:

  • Small and easy to integrate
  • The default rendering is very pretty
  • Support many languages: C#, HTML, JS, XML, SQL, etc.
  • Support extensions to customize the display: highlight specific lines, display language name, automatic link creation, etc.

#Adding code with Windows Live Writer

This is the most complicated part… Windows Live Writer is intended to write text. Moreover we can see that there is no "code" button in this editor. But fortunately, Windows Live Writer is extensible. 4 modes of extensions are possible:

  • Add/Edit simple text,
  • Add/Edit advanced text (what we chose),
  • Adding a Header / Footer,
  • Interception of sending the post to the blog.

So we wrote an extension to enter code and generate the HTML above. Here is how the extension works:

The extension adds a "Code Editor" button in the extensions menu. When clicking, a window is used to enter the code. A block is added in the text of the article. An interesting point the block is editable only via the extension. We are thus sure not to modify the HTML and the code thus remains always correctly formatted.

A usable version of the extension is available on GitHub. (Note: this is a simplified version of the extension we use)


The chosen solution has nothing specific to our blog platform, so you can use it whatever your platform (WordPress, BlogEngine.NET, Ghost, etc.). The only thing to integrate into the blog is Prismjs (CSS and JS file). For writing posts, you need to install the plugin. In short in 10 minutes it's over!

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub