This snippet is based on djangos urlize filter. It converts http:// links to youtube into youtube-embed statements, so that one can provide a simple link to a youtube video and this filter will embed it. I used it for a fun blog app.
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 | @register.filter
def youtubize(value):
"""
Converts http:// links to youtube into youtube-embed statements, so that
one can provide a simple link to a youtube video and this filter will
embed it.
Based on the Django urlize filter.
"""
text = value
# Configuration for urlize() function
LEADING_PUNCTUATION = ['(', '<', '<']
TRAILING_PUNCTUATION = ['.', ',', ')', '>', '\n', '>']
word_split_re = re.compile(r'(\s+)')
punctuation_re = re.compile('^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % \
('|'.join([re.escape(x) for x in LEADING_PUNCTUATION]),
'|'.join([re.escape(x) for x in TRAILING_PUNCTUATION])))
youtube_re = re.compile ('http://www.youtube.com/watch.v=(?P<videoid>(.+))')
words = word_split_re.split(text)
for i, word in enumerate(words):
match = punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
if middle.startswith('http://www.youtube.com/watch') or middle.startswith('http://youtube.com/watch'):
video_match = youtube_re.match(middle)
if video_match:
video_id = video_match.groups()[1]
middle = '''<object width="425" height="350">
<param name="movie" value="http://www.youtube.com/v/%s"/>
<param name="wmode" value="transparent"/>
<embed src="http://www.youtube.com/v/%s" type="application/x-shockwave-flash" wmode="transparent" width="425" height="350"/>
</object>''' % (video_id, video_id)
if lead + middle + trail != word:
words[i] = lead + middle + trail
return ''.join(words)
|
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 is awesome! Great snippet!
#
This is an awesome filter. Thanks for putting it up.
#
Thank for this useful filter. I tried to embed some youtube video, but i couldn't do it. When i insert the link, i see the link again. It doesn't convert to embeded video.
I tried this on a blog which has tinymce within the entry. Thank you for your help.
#
Please login first before commenting.