]> git.ipfire.org Git - thirdparty/jinja.git/commitdiff
Added a more convenient autoescaping function
authorArmin Ronacher <armin.ronacher@active-4.com>
Sat, 7 Jan 2017 15:07:50 +0000 (16:07 +0100)
committerArmin Ronacher <armin.ronacher@active-4.com>
Sat, 7 Jan 2017 15:07:50 +0000 (16:07 +0100)
CHANGES
jinja2/__init__.py
jinja2/utils.py
tests/test_utils.py

diff --git a/CHANGES b/CHANGES
index afc6f760f23bbc1f5d17cd2b46d1816305719049..8b7489f9d89c6630444e3266490ac1785c1a1043 100644 (file)
--- a/CHANGES
+++ b/CHANGES
@@ -41,6 +41,8 @@ Version 2.9
   propagated the same way.  The only remaining differences is the defaults
   for `with context` and `without context`.
 - The `with` and `autoescape` tags are now built-in.
+- Added the new `select_autoescape` function which helps configuring better
+  autoescaping easier.
 
 Version 2.8.2
 -------------
index cefd0d6b716d0e20a9e8e14c811e1dd514b25ae8..33724bfd07c0787dfadb825c56e0e41064415b9a 100644 (file)
@@ -55,7 +55,7 @@ from jinja2.filters import environmentfilter, contextfilter, \
      evalcontextfilter
 from jinja2.utils import Markup, escape, clear_caches, \
      environmentfunction, evalcontextfunction, contextfunction, \
-     is_undefined
+     is_undefined, select_autoescape
 
 __all__ = [
     'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',
@@ -67,6 +67,7 @@ __all__ = [
     'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',
     'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',
     'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',
+    'select_autoescape',
 ]
 
 
index 38e5edb2e3d543e518111c1aac2ae8b858e0cf8c..9bab1434cb9c32b084b419d9a03a1d021b0fbeaf 100644 (file)
@@ -488,6 +488,55 @@ except ImportError:
     pass
 
 
+def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),
+                      disabled_extensions=(),
+                      default_for_string=True,
+                      default=False):
+    """Intelligently sets the initial value of autoescaping based on the
+    filename of the template.  This is the recommended way to configure
+    autoescaping if you do not want to write a custom function yourself.
+
+    If you want to enable it for all templates created from strings or
+    for all templates with `.html` and `.xml` extensions::
+
+        from jinja2 import Environment, select_autoescape
+        env = Environment(autoescape=select_autoescape(
+            enabled_extensions=('html', 'xml'),
+            default_for_string=True,
+        ))
+
+    Example configuration to turn it on at all times except if the template
+    ends with `.txt`::
+
+        from jinja2 import Environment, select_autoescape
+        env = Environment(autoescape=select_autoescape(
+            disabled_extensions=('txt',),
+            default_for_string=True,
+            default=True,
+        ))
+
+    The `enabled_extensions` is an iterable of all the extensions that
+    autoescaping should be enabled for.  Likewise `disabled_extensions` is
+    a list of all templates it should be disabled for.  If a template is
+    loaded from a string then the default from `default_for_string` is used.
+    If nothing matches then the initial value of autoescaping is set to the
+    value of `default`.
+
+    .. versionadded:: 2.9
+    """
+    enabled_patterns = tuple('.' + x.lstrip('.') for x in enabled_extensions)
+    disabled_patterns = tuple('.' + x.lstrip('.') for x in disabled_extensions)
+    def autoescape(template_name):
+        if template_name is None:
+            return default_for_string
+        if template_name.endswith(enabled_patterns):
+            return True
+        if template_name.endswith(disabled_patterns):
+            return False
+        return default
+    return autoescape
+
+
 def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
     """Works exactly like :func:`dumps` but is safe for use in ``<script>``
     tags.  It accepts the same arguments and returns a JSON string.  Note that
index 0775a960f6302a7b92fa448a9da0952523b401fa..0cae4d4267c8b646b6e5956f90895aecd8dd0c28 100644 (file)
@@ -14,7 +14,8 @@ import pytest
 
 import pickle
 
-from jinja2.utils import LRUCache, escape, object_type_repr, urlize
+from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \
+     select_autoescape
 
 
 @pytest.mark.utils
@@ -57,6 +58,20 @@ class TestHelpers(object):
         assert object_type_repr(None) == 'None'
         assert object_type_repr(Ellipsis) == 'Ellipsis'
 
+    def test_autoescape_select(self):
+        func = select_autoescape(
+            enabled_extensions=('html', '.htm'),
+            disabled_extensions=('txt',),
+            default_for_string='STRING',
+            default='NONE',
+        )
+
+        assert func(None) == 'STRING'
+        assert func('unknown.foo') == 'NONE'
+        assert func('foo.html') == True
+        assert func('foo.htm') == True
+        assert func('foo.txt') == False
+
 
 @pytest.mark.utils
 @pytest.mark.markupleak