Login

Using Pygments with reST

Author:
joshua
Posted:
February 27, 2007
Language:
Python
Version:
Pre .96
Score:
5 (after 5 ratings)

UPDATED: This now supports an argument for the initial header level.

This is a modified version of django.contrib.markup that allows you to highlight code via pygments. The code block can be used as:

`Here's a paragraph, and a code example:

.. code:: language

*insert code here*

continue with your normal document.`

Setup: Insert the snippet into mysite/templatetags/rest.py, then add mysite to your installed apps in settings.py.

In your template, {% load rest %} and {{ mycontent|rest }}.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
from django import template
from django.conf import settings

from docutils import nodes
from docutils.parsers.rst import directives
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter


pygments_formatter = HtmlFormatter()

def pygments_directive(name, arguments, options, content, lineno,
                       content_offset, block_text, state, state_machine):
    try:
        lexer = get_lexer_by_name(arguments[0])
    except ValueError:
        # no lexer found - use the text one instead of an exception
        lexer = get_lexer_by_name('text')
    parsed = highlight(u'\n'.join(content), lexer, pygments_formatter)
    return [nodes.raw('', parsed, format='html')]
pygments_directive.arguments = (1, 0, 1) 
pygments_directive.content = 1
directives.register_directive('code', pygments_directive)


register = template.Library()

@register.filter
def rest ( value, headerlevel=2 ): 
    try:
        from docutils.core import publish_parts
    except ImportError:
        if settings.DEBUG:
            raise template.TemplateSyntaxError, "Error in {% rest %} filter: The Python docutils library isn't installed."
        return value
    else:
        docutils_settings = getattr(settings, "REST_FILTER_SETTINGS", {'initial_header_level': int(headerlevel)})
        parts = publish_parts(source=value, writer_name="html4css1", settings_overrides=docutils_settings)
        return parts["html_body"]

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.