Handy tag for generating URLs to media files

 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
from django import template
from django.conf import settings

register = template.Library()

class MediaURLNode(template.Node):
	def __init__(self, path):
		self.path = path

	def render(self, context):
		import urlparse
		import os.path
		if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.path)):
			return urlparse.urljoin(settings.MEDIA_URL, self.path);
		return ''

#@register.tag
def media(parser, token):
	"""
		Returns an absolute URL pointing to the given media file.

		The first argument is the path to the file starting from MEDIA_ROOT.
		If the file doesn't exist, empty string '' is returned.

		For example if you have the following in your settings:

		MEDIA_URL = 'http://media.example.com'

		then in your template you can get the URL for css/mystyle.css like this:

		{% media 'css/mystyle.css' %}

		This URL will be returned: http://media.example.com/css/style.css.
	"""
	bits = list(token.split_contents())
	if len(bits) != 2:
		raise TemplateSyntaxError("%r tag takes one argument" % bits[0])

	path = bits[1]
	return MediaURLNode(path[1:-1])
media = register.tag(media)

More like this

  1. Template tag for compressed CSS & JS (GAE version) by jeffar 5 years, 9 months ago
  2. Git media cache busting tag by adamlofts 4 years, 5 months ago
  3. head inclusion middleware by bowdengm 5 years, 2 months ago
  4. Load static media from secure (SSL) static server (Context Processor) by ianreardon 4 years, 6 months ago
  5. Cacheable resources by jbrisbin 5 years, 8 months ago

Comments

ubernostrum (on April 23, 2007):

This is a bit easier if you use the simple_tag decorator.

#

(Forgotten your password?)