Login

Handy tag for generating URLs to media files

Author:
amr-mostafa
Posted:
April 21, 2007
Language:
Python
Version:
.96
Score:
5 (after 5 ratings)

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.

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

Comments

ubernostrum (on April 23, 2007):

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

#

Please login first before commenting.