Created
February 1, 2015 11:52
-
-
Save joanfont/4ae7d804e4602bce7caa to your computer and use it in GitHub Desktop.
Django YouTube embed tag
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django import template | |
import re | |
register = template.Library() | |
@register.simple_tag | |
def youtube_embed(video): | |
YOUTUBE_REGEX = r'(https?://)?(www\.)?(youtube|youtu|youtube-nocookie)\.(com|be)/(watch\?v=|embed/|v/|.+\?v=)?([^&=%\?]{11})' | |
def _get_id(video): | |
match = re.match(YOUTUBE_REGEX, video) | |
return match.group(6) if match else None | |
def _get_embed_url(video_id): | |
return '//youtube.com/embed/%s?showinfo=0&controls=2&showsearch=0&rel=0' % video_id | |
_id =_get_id(video) | |
if _id: | |
embed_url = _get_embed_url(_id) | |
return '<iframe frameborder="0" webkitallowfullscreen="true"'\ | |
'width="720" height="360"'\ | |
'mozallowfullscreen="true" allowfullscreen="true"'\ | |
'src="%s"></iframe>' % embed_url | |
else: | |
return video |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment