Login

Twitterfy

Author:
dougal
Posted:
September 22, 2009
Language:
Python
Version:
1.1
Tags:
template-filter twitter hash-tag at-reply
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. @reply links and hash tags in Twitter messages by dougal 6 years, 1 month ago
  2. twitterize filter by thomasw 6 years ago
  3. Template filter to turn Twitter names into links by mrben_ 4 years, 9 months ago
  4. twitter_status by zodman 6 years, 8 months ago
  5. @reply links in Twitter messages by ryanberg 6 years, 10 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.