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
Provenance
- Commit
0020a47- Tree
e729da1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
a27a503
4 files changed+69 added−2 removed
modified:jinja2/__init__.py+2 added-1 removed
53 unmodified lines54 from jinja2.filters import environmentfilter, contextfilter, \55 evalcontextfilter56 from jinja2.utils import Markup, escape, clear_caches, \57 environmentfunction, evalcontextfunction, contextfunction, \58- is_undefined58+ is_undefined, select_autoescape59 60 __all__ = [61 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',62 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',3 unmodified lines66 '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 ]72 73 74 def _patch_async():8 unmodified linesmodified:jinja2/utils.py+49 added
486 unmodified lines487 except ImportError:488 pass489 490 491+def 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.498+499+ If you want to enable it for all templates created from strings or500+ for all templates with `.html` and `.xml` extensions::501+502+ from jinja2 import Environment, select_autoescape503+ env = Environment(autoescape=select_autoescape(504+ enabled_extensions=('html', 'xml'),505+ default_for_string=True,506+ ))507+508+ Example configuration to turn it on at all times except if the template509+ ends with `.txt`::510+511+ from jinja2 import Environment, select_autoescape512+ env = Environment(autoescape=select_autoescape(513+ disabled_extensions=('txt',),514+ default_for_string=True,515+ default=True,516+ ))517+518+ 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`.524+525+ .. 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 autoescape538+539+540 def 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 will76 unmodified linesmodified:tests/test_utils.py+16 added-1 removed
12 unmodified lines13 import pytest14 15 import pickle16 17-from jinja2.utils import LRUCache, escape, object_type_repr, urlize17+from jinja2.utils import LRUCache, escape, object_type_repr, urlize, \18+ select_autoescape19 20 21 @pytest.mark.utils22 @pytest.mark.lrucache34 unmodified lines57 assert object_type_repr(X()) == 'test_utils.X object'58 assert object_type_repr(None) == 'None'59 assert object_type_repr(Ellipsis) == 'Ellipsis'60 61+ 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+ )68 69+ 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') == False74+75+76 @pytest.mark.utils77 @pytest.mark.markupleak78 @pytest.mark.skipif(hasattr(escape, 'func_code'),79 reason='this test only tests the c extension')23 unmodified linesmodified:CHANGES+2 added
39 unmodified lines40 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.46 47 Version 2.8.248 -------------49 381 unmodified lines