Login

twitterize filter

Author:
thomasw
Posted:
April 16, 2009
Language:
Python
Version:
1.0
Score:
4 (after 4 ratings)

This filter links twitter user names prefixed with '@', hash tags, and URLs.

Usage example:

{{var|twitterize}}

Note: Do not use this in conjunction with the urlize filter. Twitterize does this for you.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
@stringfilter
def twitterize(value, autoescape=None):
	from django.utils.html import urlize
	import re
	# Link URLs
	value = urlize(value, nofollow=False, autoescape=autoescape)
	# Link twitter usernames prefixed with @
	value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b',r'\1<a href="http://twitter.com/\2">@\2</a>',value)
	# Link hash tags
	value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b',r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>',value)
	return mark_safe(value)
twitterize.is_safe=True
twitterize.needs_autoescape = True

More like this

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

Comments

dfrankow (on December 23, 2010):

This will let through arbitrary HTML, hence is open to attacks.

#

dfrankow (on December 23, 2010):

Oops, not sure about that..

#

Please login first before commenting.