пятница, 11 мая 2012 г.

django youtube video template filter

Немного переделал http://djangosnippets.org/snippets/858/ под свои нужды. Теперь фильтр выковыривает ссылки из текста (раньше фильтр обрабатывал только одну ссылку) и вставляет как oembed объект. Можно задать длину-ширину опционально: {{ content|youtube:"320x240" }} по дефолту 320x240.

# -*- coding: utf-8 -*-

from django.template.defaultfilters import stringfilter
from django import template
import re

register = template.Library()

@register.filter
@stringfilter
def youtube(url, size=None):
    regex = re.compile(r".*(http://)?(www\.)?(youtube\.com/watch\?)?v=(?P[A-Za-z0-9\-=_]{11})(\&)?.*", re.UNICODE)
    match = regex.match(url)
    if not match: return url
    video_id = match.group('id')
    
    video_w = "320"
    video_h = "240"
    if size and "x" in size:
        (video_w, video_h) = size.split('x')
    
    youtube_iframe = """
    <iframe src="http://www.youtube.com/embed/%s?fs=1&feature=oembed" frameborder="0" allowfullscreen width="%spx" height="%spx"></iframe>
    """ % (video_id, video_w, video_h)
    
    repl = re.compile(r"(http://)?(www\.)?(youtube\.com/watch\?v=)?(?P[A-Za-z0-9\-=_]{11}[^\b]*)", re.UNICODE)
    text = re.sub(repl, youtube_iframe, url)
    return text
youtube.is_safe = True # Don't escape HTML

Комментариев нет:

Отправить комментарий