from django import template
from django.template.defaultfilters import stringfilter
from django.utils.safestring import mark_safe
import string
import re
register = template.Library()
@stringfilter
@register.filter(name='jumptime')
def jumptime(text):
'''
Finds timecodes in a chunk of text and turns them into links with value attribute set to where the second of the spot to jump
Returned links also have a class of "jumpToTime" set
'''
# our regular expression to find times
r = re.compile('((\d{1,2}:)?\d{1,3}:\d{2})',re.DOTALL)
offset = 0 #used to caclulate how much text we're adding
for m in re.finditer(r,text):
timecode = m.group(1)
tc = timecode.split(':')
if len(tc) == 2:
seconds = int(tc[1]) + (int(tc[0]) * 60)
elif len(tc) == 3:
seconds = int(tc[2]) + (int(tc[1]) * 60) + (int(tc[0]) * 60 * 60)
else:
seconds = 0
if seconds != 0:
# replaces the text at the exact position it needs to be replaced, keeps track of offset
newText = "<a href='#' value='%s' class='jumpToTime'>%s</a>" % (seconds, timecode)
start = m.start() + offset
end = m.end() + offset
text = text[:start] + newText + text[end:]
offset += len(newText) - len(timecode)
return mark_safe(text)
Comments