Code

Ticket #15252: 15252.1.diff

File 15252.1.diff, 2.3 KB (added by jezdez, 3 years ago)

initial patch

Line 
1diff --git a/django/contrib/staticfiles/templatetags/__init__.py b/django/contrib/staticfiles/templatetags/__init__.py
2new file mode 100644
3index 0000000..e69de29
4diff --git a/django/contrib/staticfiles/templatetags/staticfiles.py b/django/contrib/staticfiles/templatetags/staticfiles.py
5new file mode 100644
6index 0000000..5ddff77
7--- /dev/null
8+++ b/django/contrib/staticfiles/templatetags/staticfiles.py
9@@ -0,0 +1,18 @@
10+from django import template
11+from django.conf import settings
12+from django.core.files.storage import get_storage_class
13+
14+register = template.Library()
15+
16+storage = get_storage_class(settings.STATICFILES_STORAGE)()
17+
18+
19+@register.simple_tag
20+def staticfiles_url(path):
21+    """
22+    A template tag that returns the URL to a file
23+    using staticfiles' storage backend
24+    """
25+    if storage.exists(path):
26+        return storage.url(path)
27+    return ''
28diff --git a/tests/regressiontests/staticfiles_tests/tests.py b/tests/regressiontests/staticfiles_tests/tests.py
29index 1e2b549..6ecb01f 100644
30--- a/tests/regressiontests/staticfiles_tests/tests.py
31+++ b/tests/regressiontests/staticfiles_tests/tests.py
32@@ -7,6 +7,7 @@ import sys
33 import tempfile
34 from StringIO import StringIO
35 
36+from django.template import loader, Context
37 from django.conf import settings
38 from django.contrib.staticfiles import finders, storage
39 from django.core.exceptions import ImproperlyConfigured
40@@ -85,6 +86,11 @@ class StaticFilesTestCase(TestCase):
41     def assertFileNotFound(self, filepath):
42         self.assertRaises(IOError, self._get_file, filepath)
43 
44+    def assertTemplateRenders(self, template, result, **kwargs):
45+        if isinstance(template, basestring):
46+            template = loader.get_template_from_string(template)
47+        self.assertEqual(template.render(Context(kwargs)), result)
48+
49 
50 class BuildStaticTestCase(StaticFilesTestCase):
51     """
52@@ -432,3 +438,10 @@ class TestStaticfilesDirsType(TestCase):
53 
54     def test_non_tuple_raises_exception(self):
55         self.assertRaises(ImproperlyConfigured, finders.FileSystemFinder)
56+
57+
58+class TestTemplateTag(StaticFilesTestCase):
59+
60+    def test_template_tag(self):
61+        self.assertTemplateRenders("""{% load staticfiles %}{% staticfiles_url "does/not/exist.png" %}""", "")
62+        self.assertTemplateRenders("""{% load staticfiles %}{% staticfiles_url "test/storage.txt" %}""", "/static/test/storage.txt")