Login

Template filter to convert timecodes into links

Author:
justin_h
Posted:
September 4, 2009
Language:
Python
Version:
1.1
Tags:
regex time re timecode
Score:
0 (after 0 ratings)

This template filter, "jumptime" will find any timecodes in a chunk of text and convert them to links that can be used to jump a video player to that point. E.g., If there is the string "3:05", it will be converted into a link that can be used to jump to that point. This is similar to what youtube does.

For information on how to implement, see Django's custom template tag information.

You'd use this with some javascript like this:

jQuery(document).ready(function(){ jQuery('a.jumpToTime').bind('click',function(){ player.sendEvent('PLAY'); player.sendEvent('SEEK', jQuery(this).attr('value')); }); });

 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
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)

More like this

  1. Read more link by nny777 7 years, 2 months ago
  2. Template filter to turn Twitter names into links by mrben_ 5 years, 1 month ago
  3. "Partial Templates" - an alternative to "include" by vigrid 6 years, 7 months ago
  4. Template filter for internal links in TextFields by bobtiki 9 months, 3 weeks ago
  5. youtubize template tag by TheJester 8 years, 4 months ago

Comments

Please login first before commenting.