Skip to content

Instantly share code, notes, and snippets.

@gregnewman
Forked from idan/gist:182264
Created September 7, 2009 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gregnewman/182282 to your computer and use it in GitHub Desktop.
Save gregnewman/182282 to your computer and use it in GitHub Desktop.
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.html import conditional_escape
from django.utils.safestring import mark_safe
import re
register = template.Library()
# (?:\A|[\s\.,:;'"])(@(\w{1,20}))(?!\.?\w)
twitterize_pattern = r'''
(?: # non-capturing group
\A # start: match the beginning of line
| [\s\.,:;'"] # or any of: whitespace, period, comma, colon, etc...
)
(@ # capture group \1, contains the full @username
(\w{1,20}) # capture group \2, the 1-20 char username without @
)
(?! # but don't match if followed by
\.? # zero or one periods
\w # followed by any word character
)'''
twitterize_replace = r'''
@<a class="tweetreply" href="http://twitter.com/\2">\2</a>'''
twitterize_regex = re.compile(twitterize_pattern, re.VERBOSE)
@register.filter()
@stringfilter
def twitterize(value, autoescape=None):
"""
Converts all "@replies" in plain text into clickable links, while trying
to ignore red herrings like email addresses, invalid twitter usernames.
@replies can have some leading punctuation or trailing punctuation,
but cannot
"""
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
result = twitterize_regex.sub(twitterize_replace, esc(value))
return mark_safe(result)
twitterize.is_safe = True
twitterize.needs_autoescape = True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment