Twitter template tags and filters

 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
from django.template import Library
from django.utils.safestring import mark_safe
import re

register = Library()

@register.filter
def tweet(value):
	value = re.sub(r'((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+)', '<a href="\g<0>" rel="external">\g<0></a>', value)
	value = re.sub(r'http://(yfrog|twitpic).com/(?P<id>\w+/?)', '', value)
	value = re.sub(r'#(?P<tag>\w+)', '<a href="http://search.twitter.com/search?tag=\g<tag>" rel="external">#\g<tag></a>', value)
	value = re.sub(r'@(?P<username>\w+)', '@<a href="http://twitter.com/\g<username>/" rel="external">\g<username></a>', value)
	
	return mark_safe(value)

def tweet_attachments(ex, value, max_items = -1):
	start = 0
	matches = ex.search(value, start)
	ids = []
	
	while matches:
		groupdict = matches.groupdict()
		if 'id' in groupdict:
			if not groupdict['id'] in ids:
				ids.append(groupdict['id'])
		
		start = matches.end()
		matches = ex.search(value, start)
	
	if max_items > -1:
		ids = ids[:max_items]
	
	return ids

@register.simple_tag
def yfrog_images(value, max_items = -1, lightbox = None):
	ex = re.compile(r'http://yfrog.com/(?P<id>\w+/?)')
	ids = tweet_attachments(ex, value, max_items)
	
	classes = ['yfrog-thumbnail']
	if lightbox:
		classes += [lightbox]
		extension = ':iphone'
	else:
		extension = ''
	
	urls = '\n'.join(
		[
			'<a href="http://yfrog.com/%(id)s%(extension)s" class="%(classes)s" rel="external"><img src="http://yfrog.com/%(id)s.th.jpg" /></a>' % {
				'id': i,
				'classes': ' '.join(classes),
				'extension': extension
			} for i in ids
		]
	)
	
	return mark_safe(urls)

@register.simple_tag
def twitpic_images(value, max_items = -1, lightbox = None):
	ex = re.compile(r'http://twitpic.com/(?P<id>\w+/?)')
	ids = tweet_attachments(ex, value, max_items)
	
	classes = ['twitpic-thumbnail']
	if lightbox:
		classes += [lightbox]
	
	urls = '\n'.join(
		[
			'<a href="http://twitpic.com/show/full/%(id)s" class="%(classes)s" rel="external"><img src="http://twitpic.com/show/thumb/%(id)s" /></a>' % {
				'id': i,
				'classes': ' '.join(classes),
			} for i in ids
		]
	)

	return mark_safe(urls)

More like this

  1. Twitter status tag by gmacgregor 6 years, 2 months ago
  2. Template filter to turn Twitter names into links by mrben_ 3 years, 9 months ago
  3. Analogue template filter to removetags that also removes the content of the tag by piquadrat 3 years, 5 months ago
  4. A dict template tag by Batiste 6 years ago
  5. Tags & filters for rendering search results by exogen 6 years, 1 month ago

Comments

(Forgotten your password?)