Code Highlighting

Created on Nov. 23, 2012, 10:35 a.m. by Hevok & updated by Hevok on May 2, 2013, 5:07 p.m.

Pygments is a synthax highlighter. It can be used with reST or markdown.

To highlight code in reST use the sourcecode directive followed by the specified language (e.g. python, html, django, reST):

.. sourcecode:: python

def sum(x,y):
    return x + y
def sum(x,y):
    return x + y

Numerous language are supported and can be tested by a demo app:

Markdown 2.0+ has an extension system CodeHilite that uses Pygements.

A prerequisite is to create a style-sheet that defines color for synthax highlighting:

$ pygmentize -S default -f html -a .codehilite > code.css

To use CodeHilite add the following to the template:

{% load markup %}
{{ entry.text|markdown:`codehilite` }}

To mark code block within the text, indent the block by 4 spaces, declare the language of the block in the first line prefixed by three subsequent colons:

print("Code highlighting")

In order to be sure that untrusted embedded HTML elements are not enabled include the following instead of the above:

{% load markup %}
{{ entry.text|markdown:'safe,codehilite' }}

Tags: rest, django
Categories: Tutorial
Parent: Markup

Update entry (Admin) | See changes

Comment on This Data Unit