This is a function based on django's urlize modified to show different media based on their url. It supports images, links, mp3/ogg links, youtube videos, vimeo videos and dailymotion videos.
I added a switch called mini to have two modes to show things in different places. When mini is activated it will only parse the first url provided and discard the rest as well as limiting the height.
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 | def ultralize(text, mini=False,trim_url_limit=None, nofollow=False, autoescape=False):
text = unicodedata.normalize('NFKD', text).encode('ascii','ignore')
trim_url = lambda x, limit=trim_url_limit: limit is not None and (len(x) > limit and ('%s...' % x[:max(0, limit - 3)])) or x
safe_input = isinstance(text, SafeData)
words = word_split_re.split(force_unicode(text))
nofollow_attr = nofollow and ' rel="nofollow"' or ''
has_stuff = False
for i, word in enumerate(words):
if word == "fun1":
word = "http://bleachexile.com/exec/images/emoticons/th_funone3kk.gif"
match = None
if '.' in word or '@' in word or ':' in word:
match = punctuation_re.match(word)
if match:
lead, middle, trail = match.groups()
# Make URL we want to point to.
url = None
if middle.startswith('http://') or middle.startswith('https://'):
url = urlquote(middle, safe='/&=:;#?+*')
elif middle.startswith('www.') or ('@' not in middle and \
middle and middle[0] in string.ascii_letters + string.digits and \
(middle.endswith('.org') or middle.endswith('.net') or middle.endswith('.com'))):
url = urlquote('http://%s' % middle, safe='/&=:;#?+*')
elif '@' in middle and not ':' in middle and simple_email_re.match(middle):
url = 'mailto:%s' % middle
nofollow_attr = ''
# Make link.
if url:
trimmed = trim_url(middle)
ytregex = re.compile(r"^(http://)?(www\.)?(youtube\.com/watch\?v=)(?P<id>[A-Za-z0-9\-=_]{11})")
vimeoregex = re.compile(r"^(http://)?(www\.)?(vimeo\.com/)(?P<id>\d+)")
dmregex = re.compile(r"^(http://)?(www\.)?(dailymotion\.com/video/)(?P<id>[A-Za-z0-9]+)")
ytmatch = ytregex.match(middle)
vimeomatch = vimeoregex.match(middle)
dmmatch = dmregex.match(middle)
if ytmatch:
video_id = ytmatch.group('id')
if vimeomatch:
video_id = vimeomatch.group('id')
if dmmatch:
video_id = dmmatch.group('id')
if autoescape and not safe_input:
lead, trail = escape(lead), escape(trail)
url, trimmed = escape(url), escape(trimmed)
if any(s in middle for s in ['.jpg', '.JPG', '.gif', '.GIF', '.bmp', '.BMP', '.png', '.PNG', '.jpeg', '.JPEG', 'gstatic.com/images']):
if has_stuff and mini:
middle = ''
else:
if mini:
middle = '<a rel="lightbox" href="%s"><img class="contentimg" style="display:block; max-width:100%%;max-height:300px; padding-top:5px; margin-bottom:3px" src="%s"></a>' % (url, url)
else:
middle = '<a rel="lightbox" href="%s"><img class="contentimg" style="display:block; max-width:100%%;padding-top:5px; margin-bottom:3px" src="%s"></a>' % (url, url)
has_stuff = True
elif middle.startswith("http://www.youtube.com/watch?v=") or middle.startswith("www.youtube.com/watch?v="):
if ytmatch:
if has_stuff and mini:
middle = ''
else:
middle = "<iframe style=\"display:block;padding-top:5px; margin-bottom:3px\" title=\"YouTube video player\" width=\"600\" height=\"365\" src=\"http://www.youtube.com/embed/%s\" frameborder=\"0\" allowfullscreen></iframe>" % (video_id + "?autohide=1&wmode=transparent")
has_stuff = True
elif middle.startswith("http://www.vimeo.com") or middle.startswith("www.vimeo.com") or middle.startswith("vimeo.com") or middle.startswith("http://vimeo.com"):
if vimeomatch:
if has_stuff and mini:
middle = ''
else:
middle = "<iframe style='display:block;'src=\"http://player.vimeo.com/video/%s?title=0&byline=0&portrait=0\" width=\"600\" height=\"405\" frameborder=\"0\"></iframe>" % (video_id)
has_stuff = True
elif middle.startswith("http://www.dailymotion.com") or middle.startswith("www.dailymotion.com") or middle.startswith("dailymotion.com") or middle.startswith("http://dailymotion.com"):
if dmmatch:
if has_stuff and mini:
middle = ''
else:
middle = "<iframe frameborder='0' width='560' height='315' src='http://www.dailymotion.com/embed/video/%s?width=560'></iframe>" % (video_id)
has_stuff = True
elif middle.endswith(".ogg") or middle.endswith(".mp3"):
if has_stuff and mini:
middle = ''
else:
middle = "<audio style=\"display:block;padding-top:5px; margin-bottom:6px\" src=\"%s\" controls=\"controls\"></audio>" % (url)
has_stuff = True
else:
if has_stuff and mini:
middle = ''
else:
middle = "<a style='display:block;' target='_blank' href='%s'%s>%s</a>" % (url, nofollow_attr, trimmed)
has_stuff = True
words[i] = mark_safe('%s%s%s' % (lead, middle, trail))
else:
if safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
elif safe_input:
words[i] = mark_safe(word)
elif autoescape:
words[i] = escape(word)
return mark_safe(u''.join(words))
ultralize.is_safe=True
ultralize.needs_autoescape = True
ultralize = stringfilter(ultralize)
register.filter(ultralize)
ultralize = allow_lazy(ultralize, unicode)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
- Help text hyperlinks by sa2812 1 year, 6 months ago
Comments
Nice, ty
#
Please login first before commenting.