Grep template tag for Django

Nice and easy couple of [Django template tags][tagsandfilters] that filter lines of text using a regular expression. I had a block of text where I wanted to remove some of the lines but not others.

You can use `grep` to remove any lines that do not match your pattern:

>>> s = ‘The quick brown fox’
>>> grep(s, ‘quick’)
u’The quick brown fox’

And its converse `grepv` to remove any lines that do match your pattern:

>>> s = ‘The quick brown fox’
>>> grepv(s, ‘quick’)

>>> s2 = s + ‘\nJumps over the lazy dog’
>>> grepv(s2, ‘quick’)
u’Jumps over the lazy dog’

Stick it in a module in your Django application ([documentation][customtags]), then load it up at the top of a template.

from django import template
from django.template.defaultfilters import stringfilter
import re

register = template.Library()

@register.filter
@stringfilter
def grep(value, arg):
“””Lines that do not match the regular expression are removed.”””
pattern = re.compile(arg)
lines = [line for line in re.split(r'[\r\n]’, value) if pattern.search(line)]
return ‘\n’.join(lines)

@register.filter
@stringfilter
def grepv(value, arg):
“””Lines that match the regular expression are removed.”””
pattern = re.compile(arg)
lines = [line for line in re.split(r'[\r\n]’, value) if not pattern.search(line)]
return ‘\n’.join(lines)

[tagsandfilters]: http://docs.djangoproject.com/en/dev/ref/templates/builtins/
[customtags]: http://docs.djangoproject.com/en/dev/howto/custom-template-tags/

Leave a Reply

Your email address will not be published. Required fields are marked *