Created
September 7, 2009 10:14
-
-
Save idan/182264 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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