Code highlighting in Django templates using Pygments

If you want to place higlighting code in your Django powered site, the great tool is Pygments but it's set up will take a while. Here is an example how you can set it up nicely and pretty fast, using this snippet code.

Follow next steps:

  • 1. Install Pygments
  • 2. Decide which pygments style you want to use by trying them out on the pygments site
  • 3. Create a pygments css file using whichever style you liked from the pygments site. Open your terminal and use the pygmentize command to generate a CSS file, for marking up your code.
  • pygmentize -S default -f html > default.css

    Include generated file in your page.

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

    4. Add following filter to your application:

    #-*- coding: UTF-8 -*-
    from django import template
    import re
    import pygments
    from pygments.lexers import LEXERS, get_lexer_by_name
    from pygments import highlight
    from pygments.formatters import HtmlFormatter
    register = template.Library()
    regex = re.compile(r'<code>(.*?)</code>', re.DOTALL)
    def gsailpygment(value):
            last_end = 0
            to_return = ''
            found = 0
            for match_obj in regex.finditer(value):
                code_string =
                    lexer = pygments.lexers.guess_lexer(code_string)
                except ValueError:
                    lexer = pygments.lexers.PythonLexer()
                pygmented_string = pygments.highlight(code_string, lexer, pygments.formatters.HtmlFormatter())
                to_return = to_return + value[last_end:match_obj.start(1)] + pygmented_string
                last_end = match_obj.end(1)
                found = found + 1
            to_return = to_return + value[last_end:]
            return to_return
            return value

    5. You need to wrap the code you which want to highlight with <code> tag.

    6. In your template load your filter and use it together with safe filter.

    {{ value|gsailpygment|safe }}