Python-Markdown ships with the CodeHilite Extension for highlighting code blocks. No need to use "templates" (in fact Markdown files would not generally be passed through templates, although it is possible if you wanted to write the custom code for it -- see an explanation here).
Simply enable the extension and define the language of the code block on the first line (as explained in the documentation):
:::python
import random
# Generate a random integer in the range 10 to 49.
i = random.randrange(10,50)
print 'Your number is', i
If you also enable Fenced Code Blocks, you can also define the language on them (which eliminates the need to indent the code blocks):
```ruby
for i in (1..4)
print i," "
end
```
Under the hood, CodeHilite uses Pygments to highlight the code, so any language supported by Pygments is automatically supported.
Of course, for this to work you need to enable the extensions. Without any information about how you are using Markdown from Django, I can only provide a few pointers.
If you are calling the Markdown library directly from Python code, then simply include the extensions in the call to markdown.markdown
:
body = markdown.markdown(source, extensions=['markdown.extensions.codehilite', 'markdown.extensions.fenced_code'])
Otherwise, you may find the django_markdown library to be helpful. It has a setting for MARKDOWN_EXTENSIONS
which you would need to set in your Django settings file:
MARKDOWN_EXTENSIONS = ['markdown.extensions.codehilite', 'markdown.extensions.fenced_code']
Finally, you will need the CSS to tell the browser how to style the highlighted code. The Pygments project provides some default CSS styles which you may find to be a useful starting point (those CSS styles have been neatly packaged up by richeland). You will need to add that CSS to the CSS used by your site (the specifics of which depend on how your Django site is configured and therefore is excluded from this answer).