Code

Ticket #4105: media_tag.diff

File media_tag.diff, 1.6 KB (added by Amr Mostafa, 7 years ago)
Line 
1Index: django/template/defaulttags.py
2===================================================================
3--- django/template/defaulttags.py      (revision 5056)
4+++ django/template/defaulttags.py      (working copy)
5@@ -374,6 +374,17 @@
6         context.pop()
7         return output
8 
9+class MediaURLNode(Node):
10+    def __init__(self, path):
11+        self.path = path
12+
13+    def render(self, context):
14+        import urlparse
15+        import os.path
16+        if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.path)):
17+            return urlparse.urljoin(settings.MEDIA_URL, self.path);
18+        return ''
19+
20 #@register.tag
21 def comment(parser, token):
22     """
23@@ -1009,3 +1020,29 @@
24     parser.delete_first_token()
25     return WithNode(var, name, nodelist)
26 do_with = register.tag('with', do_with)
27+
28+#@register.tag
29+def media(parser, token):
30+    """
31+    Returns an absolute URL pointing to the given media file.
32+
33+    The first argument is the path to the file starting from MEDIA_ROOT.
34+    If the file doesn't exist, empty string '' is returned.
35+
36+    For example if you have the following in your settings:
37+
38+        MEDIA_URL = 'http://media.example.com'
39+
40+    then in your template you can get the URL for css/mystyle.css like this:
41+
42+        {% media 'css/mystyle.css' %}
43+
44+    This URL will be returned: http://media.example.com/css/style.css.
45+    """
46+    bits = list(token.split_contents())
47+    if len(bits) != 2:
48+        raise TemplateSyntaxError("%r tag takes one argument" % bits[0])
49+
50+    path = bits[1]
51+    return MediaURLNode(path[1:-1])
52+media = register.tag(media)