My Site
Categories
Converting from TextPattern to Django
I like TextPattern a lot, but it doesn't seem to work well for programmers. I couldn't ever find a syntax highlighting plugin (that worked) for it, and even when I did figure out a way to post code TextPattern would try to format it.

So, I finally had a reason to learn Django, and here is the product. I even implemented my own syntax highlighting filter (Josh Simpson's idea to do this is actually what finally made me want to switch away from TextPattern in the first place):

 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
from django import template
from pygments import highlight
from pygments.lexers import get_lexer_by_name
from pygments.formatters import HtmlFormatter
from django.template import Context, loader
from django.template.defaultfilters import stringfilter
import re

register = template.Library()

@register.filterclass="nd">@register.filter class="p">(name='code_highlight')
@stringfilter
def code_highlight(value):
    """ 
        Checks for <source lang='lang'> tags in the article, and runs them
        through pygments for syntax highlighting
    """
    t = loader.get_template('codeblock.html')

    regex = re.compile(r'(<source lang=([\'"])(\w+)\2>(.*?)</source>)',
        re.DOTALL)
    items = regex.findall(value)

    for (all, crap, lang, text) in items:
        lexer = get_lexer_by_name(lang, stripall=True)
        formatter = HtmlFormatter(linenos=True, cssclass="syntax")
        result = highlight(text, lexer, formatter)

        c = Context({
            'code_block': result
        })

        value = value.replace(all, t.render(c))

    return value

There's still a lot of work to do on it, but I'll get the old posts migrated soon.
Filed under: Miscellaneous, Django
Comments:

No comments have been added yet

Add a comment:
captcha

Optional, for comment reply notifications
 
Note: If you enter your email address, you will be subscribed to this article and will recieve comment updates via email. This is the only thing your address will be used for. A link will be provided at the end of each email that will allow you to unsubscribe should you need to, or you can go to http://synicworld.com//unsubscribe to unsubscribe from any/all updates.