Login

YouTube Template Filter

Author:
jgeewax
Posted:
July 5, 2008
Language:
Python
Version:
.96
Tags:
template filter youtube embed
Score:
3 (after 3 ratings)

Given a youtube url (can copy and paste right from the browser) turns the url into an embedded video.

If you put this in your app's templatetags/filters.py, you can do the following

{{ object.youtube_url|youtube }}

and it would embed the youtube video.

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

register = template.Library()

@register.filter
@stringfilter
def youtube(url):
    regex = re.compile(r"^(http://)?(www\.)?(youtube\.com/watch\?v=)?(?P<id>[A-Za-z0-9\-=_]{11})")
    match = regex.match(url)
    if not match: return ""
    video_id = match.group('id')
    return """
    <object width="425" height="344">
    <param name="movie" value="http://www.youtube.com/watch/v/%s"></param>
    <param name="allowFullScreen" value="true"></param>
    <embed src="http://www.youtube.com/watch/v/%s" type="application/x-shockwave-flash" allowfullscreen="true" width="425" height="344"></embed>
    </object>
    """ % (video_id, video_id)
youtube.is_safe = True # Don't escape HTML

More like this

  1. youtubize template tag by TheJester 8 years, 4 months ago
  2. "Youtube watch link to embed" custom tag. by I159 3 years, 11 months ago
  3. Get the youtube video thumbnail url template filter by fitoria 4 years, 10 months ago
  4. convert youtube url for iframe, js api by ivanff 2 years, 5 months ago
  5. ultralize by catellar 4 years ago

Comments

KpoH (on July 5, 2008):

does youtube already support OEmbed?

#

maccesch (on May 31, 2011):

it does today :)

#

ekin (on July 8, 2011):

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.