Login

Twitterfy

Author:
dougal
Posted:
September 22, 2009
Language:
Python
Version:
1.1
Score:
3 (after 3 ratings)

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

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

dfrankow (on December 23, 2010):

This may let through arbitrary HTML, i.e. be subject to attack.

#

dfrankow (on December 23, 2010):

Oops, not sure about that..

#

Please login first before commenting.