Skip to content
Myr

Added a more convenient autoescaping function

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent a27a503 · Browse files · 4 files+69 added−2 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+69 added−2 removed

  • tests:+16 added−1 removed
  • other:+53 added−1 removed

4 files+69 added−2 removed

modified:jinja2/__init__.py+2 added-1 removed
53 unmodified lines
54from jinja2.filters import environmentfilter, contextfilter, \55 evalcontextfilter56from jinja2.utils import Markup, escape, clear_caches, \57 environmentfunction, evalcontextfunction, contextfunction, \58 is_undefined58 is_undefined, select_autoescape5960__all__ = [61 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',62 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',
3 unmodified lines
66 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',69 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',70 'select_autoescape',71]727374def _patch_async():
8 unmodified lines
modified:jinja2/utils.py+49 added
486 unmodified lines
487except ImportError:488 pass489490491def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),492 disabled_extensions=(),493 default_for_string=True,494 default=False):495 """Intelligently sets the initial value of autoescaping based on the496 filename of the template. This is the recommended way to configure497 autoescaping if you do not want to write a custom function yourself.498499 If you want to enable it for all templates created from strings or500 for all templates with `.html` and `.xml` extensions::501502 from jinja2 import Environment, select_autoescape503 env = Environment(autoescape=select_autoescape(504 enabled_extensions=('html', 'xml'),505 default_for_string=True,506 ))507508 Example configuration to turn it on at all times except if the template509 ends with `.txt`::510511 from jinja2 import Environment, select_autoescape512 env = Environment(autoescape=select_autoescape(513 disabled_extensions=('txt',),514 default_for_string=True,515 default=True,516 ))517518 The `enabled_extensions` is an iterable of all the extensions that519 autoescaping should be enabled for. Likewise `disabled_extensions` is520 a list of all templates it should be disabled for. If a template is521 loaded from a string then the default from `default_for_string` is used.522 If nothing matches then the initial value of autoescaping is set to the523 value of `default`.524525 .. versionadded:: 2.9526 """527 enabled_patterns = tuple('.' + x.lstrip('.') for x in enabled_extensions)528 disabled_patterns = tuple('.' + x.lstrip('.') for x in disabled_extensions)529 def autoescape(template_name):530 if template_name is None:531 return default_for_string532 if template_name.endswith(enabled_patterns):533 return True534 if template_name.endswith(disabled_patterns):535 return False536 return default537 return autoescape538539540def htmlsafe_json_dumps(obj, dumper=None, **kwargs):541 """Works exactly like :func:`dumps` but is safe for use in ``<script>``542 tags. It accepts the same arguments and returns a JSON string. Note that543 this is available in templates through the ``|tojson`` filter which will
76 unmodified lines
modified:tests/test_utils.py+16 added-1 removed
12 unmodified lines
13import pytest1415import pickle1617from jinja2.utils import LRUCache, escape, object_type_repr, urlize17from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18 select_autoescape192021@pytest.mark.utils22@pytest.mark.lrucache
34 unmodified lines
57 assert object_type_repr(X()) == 'test_utils.X object'58 assert object_type_repr(None) == 'None'59 assert object_type_repr(Ellipsis) == 'Ellipsis'6061 def test_autoescape_select(self):62 func = select_autoescape(63 enabled_extensions=('html', '.htm'),64 disabled_extensions=('txt',),65 default_for_string='STRING',66 default='NONE',67 )6869 assert func(None) == 'STRING'70 assert func('unknown.foo') == 'NONE'71 assert func('foo.html') == True72 assert func('foo.htm') == True73 assert func('foo.txt') == False747576@pytest.mark.utils77@pytest.mark.markupleak78@pytest.mark.skipif(hasattr(escape, 'func_code'),79 reason='this test only tests the c extension')
23 unmodified lines
modified:CHANGES+2 added
39 unmodified lines
40 between the different include and import constructs. Context is now always41 propagated the same way. The only remaining differences is the defaults42 for `with context` and `without context`.43- The `with` and `autoescape` tags are now built-in.44- Added the new `select_autoescape` function which helps configuring better45 autoescaping easier.4647Version 2.8.248-------------49
381 unmodified lines