Improved version of my snippet #1346. Now works correctly with multiple usernames and hash tags.
Both twitter usernames and hashtags are converted into links to twitter profiles and twitter search.
Updated, forgot about underscores in usernames.
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 | import re
from django.utils.safestring import mark_safe
from django import template
register = template.Library()
@register.filter(name='twitterfy')
def twitterfy(tweet):
# find hashtags
pattern = re.compile(r"(?P<start>.?)#(?P<hashtag>[A-Za-z0-9_]+)(?P<end>.?)")
# replace with link to search
link = r'\g<start>#<a href="http://search.twitter.com/search?q=\g<hashtag>" title="#\g<hashtag> search Twitter">\g<hashtag></a>\g<end>'
text = pattern.sub(link,tweet)
# find usernames
pattern = re.compile(r"(?P<start>.?)@(?P<user>[A-Za-z0-9_]+)(?P<end>.?)")
# replace with link to profile
link = r'\g<start>@<a href="http://twitter.com/\g<user>" title="#\g<user> on Twitter">\g<user></a>\g<end>'
text = pattern.sub(link,text)
return mark_safe(text)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
This may let through arbitrary HTML, i.e. be subject to attack.
#
Oops, not sure about that..
#
Please login first before commenting.