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)

Comments

ubernostrum (on April 23, 2007):

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

#

Amr Mostafa (on April 24, 2007):

Nice, Simplicity++!

Btw, the link refers to 'this' snippet (#195). The correct link for ubernostrum simpler media tag is here

#

(Forgotten your password?)

You may use Markdown syntax here, but raw HTML will be removed.