- 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
- Add Toggle Switch Widget to Django Forms by OgliariNatan 1 month, 3 weeks ago
- get_object_or_none by azwdevops 5 months, 2 weeks ago
- Mask sensitive data from logger by agusmakmun 7 months, 1 week ago
- Template tag - list punctuation for a list of items by shapiromatron 1 year, 9 months ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 9 months ago
Comments
This is a bit easier if you use the simple_tag decorator.
#
Please login first before commenting.