autoescape no longer is a plain boolean value but can also be a function
Before adoption: this commit came in with the history the project adopted, so no landing records it.
to enable or disable autoescaping for certain filenames (or file extensions for that matter) --HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent cedb482 · Browse files · 6 files·+66 added−8 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+66 added−8 removed
- other:+66 added−8 removed
Provenance
- Commit
1da23d1- Tree
e65ae3c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
cedb482
6 files changed+66 added−8 removed
modified:docs/api.rst+32 added
218 unmodified lines219 .. autoclass:: jinja2.environment.TemplateStream()220 :members: disable_buffering, enable_buffering, dump221 222 223+Autoescaping224+------------225+226+.. versionadded:: 2.4227+228+As of Jinja 2.4 the preferred way to do autoescaping is to enable the229+:ref:`autoescape-extension` and to configure a sensible default for230+autoescaping. This makes it possible to enable and disable autoescaping231+on a per-template basis (HTML versus text for instance).232+233+Here a recommended setup that enables autoescaping for templates ending234+in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default235+for all other extensions::236+237+ def guess_autoescape(template_name):238+ if template_name is None or '.' not in template_name:239+ return False240+ ext = template_name.rsplit('.', 1)[1]241+ return ext in ('html', 'htm', 'xml')242+243+ env = Environment(autoescape=guess_autoescape,244+ loader=PackageLoader('mypackage'),245+ extensions=['jinja2.ext.autoescape'])246+247+When implementing a guessing autoescape function, make sure you also248+accept `None` as valid template name. This will be passed when generating249+templates from strings.250+251+Inside the templates the behaviour can be temporarily changed by using252+the `autoescape` block (see :ref:`autoescape-overrides`).253+254+255 .. _identifier-naming:256 257 Notes on Identifiers258 --------------------529 unmodified linesmodified:jinja2/testsuite/api.py+18 added-1 removed
15 unmodified lines16 from jinja2.testsuite import JinjaTestCase17 18 from jinja2 import Environment, Undefined, DebugUndefined, \19 StrictUndefined, UndefinedError, Template, meta, \20- is_undefined, Template20+ is_undefined, Template, DictLoader21 from jinja2.utils import Cycler22 23 env = Environment()24 50 unmodified lines75 assert env.select_template([t]) is t76 assert env.get_or_select_template([t]) is t77 assert env.get_or_select_template(t) is t78 79+ def test_autoescape_autoselect(self):80+ def select_autoescape(name):81+ if name is None or '.' not in name:82+ return False83+ return name.endswith('.html')84+ env = Environment(autoescape=select_autoescape,85+ loader=DictLoader({86+ 'test.txt': '{{ foo }}',87+ 'test.html': '{{ foo }}'88+ }))89+ t = env.get_template('test.txt')90+ assert t.render(foo='<foo>') == '<foo>'91+ t = env.get_template('test.html')92+ assert t.render(foo='<foo>') == '<foo>'93+ t = env.from_string('{{ foo }}')94+ assert t.render(foo='<foo>') == '<foo>'95 96+97 class MetaTestCase(JinjaTestCase):98 99 def test_find_undeclared_variables(self):100 ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')117 unmodified linesmodified:jinja2/compiler.py+1 added-1 removed
759 unmodified lines760 # -- Statement Visitors761 762 def visit_Template(self, node, frame=None):763 assert frame is None, 'no root frame allowed'764- eval_ctx = EvalContext(self.environment)764+ eval_ctx = EvalContext(self.environment, self.name)765 766 from jinja2.runtime import __all__ as exported767 self.writeline('from __future__ import division')768 self.writeline('from jinja2.runtime import ' + ', '.join(exported))865 unmodified linesmodified:jinja2/environment.py+7 added-1 removed
158 unmodified lines159 160 `autoescape`161 If set to true the XML/HTML autoescaping feature is enabled by162 default. For more details about auto escaping see163- :class:`~jinja2.utils.Markup`.163+ :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also164+ be a callable that is passed the template name and has to165+ return `True` or `False` depending on autoescape should be166+ enabled by default.167 168+ .. versionchanged:: 2.4169+ `autoescape` can now be a function170+171 `loader`172 The template loader for this environment.173 174 `cache_size`916 unmodified linesmodified:jinja2/nodes.py+5 added-2 removed
70 unmodified lines71 """Holds evaluation time information. Custom attributes can be attached72 to it in extensions.73 """74 75- def __init__(self, environment):76- self.autoescape = environment.autoescape75+ def __init__(self, environment, template_name=None):76+ if callable(environment.autoescape):77+ self.autoescape = environment.autoescape(template_name)78+ else:79+ self.autoescape = environment.autoescape80 self.volatile = False81 82 def save(self):83 return self.__dict__.copy()791 unmodified linesmodified:jinja2/runtime.py+3 added-3 removed
75 unmodified lines76 self.__context = context77 78 def __getitem__(self, name):79 blocks = self.__context.blocks[name]80- wrap = self.__context.environment.autoescape and \80+ wrap = self.__context.eval_ctx.autoescape and \81 Markup or (lambda x: x)82 return BlockReference(name, self.__context, blocks, 0)83 84 def __repr__(self):28 unmodified lines113 def __init__(self, environment, parent, name, blocks):114 self.parent = parent115 self.vars = {}116 self.environment = environment117- self.eval_ctx = EvalContext(self.environment)117+ self.eval_ctx = EvalContext(self.environment, name)118 self.exported_vars = set()119 self.name = name120 121 # create the initial mapping of blocks. Whenever template inheritance134 unmodified lines256 257 @internalcode258 def __call__(self):259 rv = concat(self._stack[self._depth](self._context))260- if self._context.environment.autoescape:260+ if self._context.eval_ctx.autoescape:261 rv = Markup(rv)262 return rv263 264 272 unmodified lines