@register.assignment_tag def get_video_urls(obj, attr_name=None): """ {% get_video_urls url as url_object %} or \ get object attribute {% get_video_urls obj "url" as url_object %} {{ url_object }} original url {{ url_object.video_id }} original url or video_id {{ url_object.resource }} youtube, vimeo, None {{ url_object.iframe_url }} original url or iframe_url {{ url_object.js_api_url }} original url or js_api_url """ if not isinstance(obj, basestring): url = getattr(obj, attr_name) elif not attr_name: url = obj else: raise AttributeError class VideoId(str): def __new__(cls, *args, **kwargs): video_id, resource = args new_class = str.__new__(cls, video_id) new_class.resource = resource new_class.video_id = video_id if resource == 'youtube': new_class.iframe_url = 'http://www.youtube.com/embed/%s' % video_id new_class.js_api_url = 'http://www.youtube.com/watch?v=%s' % video_id elif resource == 'vimeo': new_class.iframe_url = 'http://player.vimeo.com/video/%s' % video_id new_class.js_api_url = 'http://player.vimeo.com/video/%s?api=1&player_id=vimeoplayer' % video_id else: new_class.iframe_url = video_id new_class.js_api_url = video_id return new_class def __repl(m): repl = m.groupdict() result = '' if repl.has_key('video_youtube_id'): result = repl['video_youtube_id'] + '__and__' + 'youtube' elif repl.has_key('video_vimeo_id'): result = repl['video_vimeo_id'] + '__and__' + 'vimeo' return result result = None matches = None if url: rs = [re.compile(r"^https?\:\/\/(www\.)?youtu\.be\/(?P[^\/]*)\??.*$"), re.compile(r"^https?\:\/\/(www\.)?youtube\.(com|nl|ru).*v=(?P.*)\&?.*$"), re.compile(r"^https?\:\/\/(www\.)?youtube\.(com|nl|ru)\/embed\/(?P[^\/]*)\??.*$"), re.compile(r"^https?\:\/\/(www\.)?vimeo\.com\/(?P[^\/]*)\??.*$"),] for r in rs: result, matches = r.subn(__repl, url) if matches: return VideoId(*result.split('__and__')) if not matches: return VideoId(result) return result