return 42;

by Jan Wedel

Markdown and CodeHilite

When I implemented the blog, I knew that I needed code blocks and some other formatting options. I was thinking whether to use

  • HTML
  • Some proprietary syntax using regex e.g.
  • Markdown

for getting it done. I was already using Markdown for ideas, project planning etc. so I chose the latter, especially when I looked at how to implement it in Python. Plus, I was working with some web applications that provide a WYSIWYG editor which then internally stores the text as HTML. This was so broken and resulted in weird effect that I was absolutely sure not to do that. I wanted to write plain text that is only interpreted when being displayed.

So, implementing this was so elegant and flexible:

pip install markdown

which installs the Markdown Python module. Then, in Django when I retrieve the plain text content from the model, I had to do:

import markdown

(...)
return markdown.markdown(self.content)

Easy, right? That call parses the plain markdown annotated text, and adds the appropriate HTML tags. Now, the Markdown module also supports extensions. One of them is CodeHilite. This will guess the use programming language or you specify it by yourself and then add additional HTML and CSS classes to the code. This requires pygments python module:

pip install pygments

Then you'll just add an argument to call:

return markdown.markdown(self.content, extensions=['codehilite'])

One last thing is to add the some CSS for the code highlighting theme. Check here for some themes. I'm using monokai.css in this blog. Copy it to your statics directory and load it in you base template:

<link rel="stylesheet" type="text/css" href="{% static 'core/styles/monokai.css' %}" />

That's it.


Jan Wedel's DEV Profile