|
@@ -1,9 +1,11 @@
|
|
|
from urlparse import urljoin
|
|
|
from django import template
|
|
|
+from django.template.base import Node
|
|
|
from django.utils.encoding import iri_to_uri
|
|
|
|
|
|
register = template.Library()
|
|
|
|
|
|
+
|
|
|
class PrefixNode(template.Node):
|
|
|
|
|
|
def __repr__(self):
|
|
@@ -48,6 +50,7 @@ class PrefixNode(template.Node):
|
|
|
context[self.varname] = prefix
|
|
|
return ''
|
|
|
|
|
|
+
|
|
|
@register.tag
|
|
|
def get_static_prefix(parser, token):
|
|
|
"""
|
|
@@ -66,6 +69,7 @@ def get_static_prefix(parser, token):
|
|
|
"""
|
|
|
return PrefixNode.handle_token(parser, token, "STATIC_URL")
|
|
|
|
|
|
+
|
|
|
@register.tag
|
|
|
def get_media_prefix(parser, token):
|
|
|
"""
|
|
@@ -84,19 +88,70 @@ def get_media_prefix(parser, token):
|
|
|
"""
|
|
|
return PrefixNode.handle_token(parser, token, "MEDIA_URL")
|
|
|
|
|
|
-@register.simple_tag
|
|
|
-def static(path):
|
|
|
+
|
|
|
+class StaticNode(Node):
|
|
|
+ def __init__(self, varname=None, path=None):
|
|
|
+ if path is None:
|
|
|
+ raise template.TemplateSyntaxError(
|
|
|
+ "Static template nodes must be given a path to return.")
|
|
|
+ self.path = path
|
|
|
+ self.varname = varname
|
|
|
+
|
|
|
+ def url(self, context):
|
|
|
+ path = self.path.resolve(context)
|
|
|
+ return self.handle_simple(path)
|
|
|
+
|
|
|
+ def render(self, context):
|
|
|
+ url = self.url(context)
|
|
|
+ if self.varname is None:
|
|
|
+ return url
|
|
|
+ context[self.varname] = url
|
|
|
+ return ''
|
|
|
+
|
|
|
+ @classmethod
|
|
|
+ def handle_simple(cls, path):
|
|
|
+ return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
|
|
|
+
|
|
|
+ @classmethod
|
|
|
+ def handle_token(cls, parser, token):
|
|
|
+ """
|
|
|
+ Class method to parse prefix node and return a Node.
|
|
|
+ """
|
|
|
+ bits = token.split_contents()
|
|
|
+
|
|
|
+ if len(bits) < 2:
|
|
|
+ raise template.TemplateSyntaxError(
|
|
|
+ "'%s' takes at least one argument (path to file)" % bits[0])
|
|
|
+
|
|
|
+ path = parser.compile_filter(bits[1])
|
|
|
+
|
|
|
+ if len(bits) >= 2 and bits[-2] == 'as':
|
|
|
+ varname = bits[3]
|
|
|
+ else:
|
|
|
+ varname = None
|
|
|
+
|
|
|
+ return cls(varname, path)
|
|
|
+
|
|
|
+
|
|
|
+@register.tag('static')
|
|
|
+def do_static(parser, token):
|
|
|
"""
|
|
|
Joins the given path with the STATIC_URL setting.
|
|
|
|
|
|
Usage::
|
|
|
|
|
|
- {% static path %}
|
|
|
+ {% static path [as varname] %}
|
|
|
|
|
|
Examples::
|
|
|
|
|
|
{% static "myapp/css/base.css" %}
|
|
|
{% static variable_with_path %}
|
|
|
+ {% static "myapp/css/base.css" as admin_base_css %}
|
|
|
+ {% static variable_with_path as varname %}
|
|
|
|
|
|
"""
|
|
|
- return urljoin(PrefixNode.handle_simple("STATIC_URL"), path)
|
|
|
+ return StaticNode.handle_token(parser, token)
|
|
|
+
|
|
|
+
|
|
|
+def static(path):
|
|
|
+ return StaticNode.handle_simple(path)
|