Login

Template filter to convert timecodes into links

Author:
justin_h
Posted:
September 4, 2009
Language:
Python
Version:
1.1
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. Template tag - list punctuation for a list of items by shapiromatron 9 months, 3 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 4 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 5 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.