Ticket #4105: media_tag.diff

File media_tag.diff, 1.6 KB (added by Amr Mostafa, 8 years ago)
  • django/template/defaulttags.py

     
    374374        context.pop()
    375375        return output
    376376
     377class MediaURLNode(Node):
     378    def __init__(self, path):
     379        self.path = path
     380
     381    def render(self, context):
     382        import urlparse
     383        import os.path
     384        if os.path.exists(os.path.join(settings.MEDIA_ROOT, self.path)):
     385            return urlparse.urljoin(settings.MEDIA_URL, self.path);
     386        return ''
     387
    377388#@register.tag
    378389def comment(parser, token):
    379390    """
     
    10091020    parser.delete_first_token()
    10101021    return WithNode(var, name, nodelist)
    10111022do_with = register.tag('with', do_with)
     1023
     1024#@register.tag
     1025def media(parser, token):
     1026    """
     1027    Returns an absolute URL pointing to the given media file.
     1028
     1029    The first argument is the path to the file starting from MEDIA_ROOT.
     1030    If the file doesn't exist, empty string '' is returned.
     1031
     1032    For example if you have the following in your settings:
     1033
     1034        MEDIA_URL = 'http://media.example.com'
     1035
     1036    then in your template you can get the URL for css/mystyle.css like this:
     1037
     1038        {% media 'css/mystyle.css' %}
     1039
     1040    This URL will be returned: http://media.example.com/css/style.css.
     1041    """
     1042    bits = list(token.split_contents())
     1043    if len(bits) != 2:
     1044        raise TemplateSyntaxError("%r tag takes one argument" % bits[0])
     1045
     1046    path = bits[1]
     1047    return MediaURLNode(path[1:-1])
     1048media = register.tag(media)
Back to Top