Skip to content
Myr

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

6 files+66 added−8 removed

modified:docs/api.rst+32 added
218 unmodified lines
219.. autoclass:: jinja2.environment.TemplateStream()220 :members: disable_buffering, enable_buffering, dump221222223Autoescaping224------------225226.. versionadded:: 2.4227228As of Jinja 2.4 the preferred way to do autoescaping is to enable the229:ref:`autoescape-extension` and to configure a sensible default for230autoescaping. This makes it possible to enable and disable autoescaping231on a per-template basis (HTML versus text for instance).232233Here a recommended setup that enables autoescaping for templates ending234in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default235for all other extensions::236237 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')242243 env = Environment(autoescape=guess_autoescape,244 loader=PackageLoader('mypackage'),245 extensions=['jinja2.ext.autoescape'])246247When implementing a guessing autoescape function, make sure you also248accept `None` as valid template name. This will be passed when generating249templates from strings.250251Inside the templates the behaviour can be temporarily changed by using252the `autoescape` block (see :ref:`autoescape-overrides`).253254255.. _identifier-naming:256257Notes on Identifiers258--------------------
529 unmodified lines
modified:jinja2/testsuite/api.py+18 added-1 removed
15 unmodified lines
16from jinja2.testsuite import JinjaTestCase1718from jinja2 import Environment, Undefined, DebugUndefined, \19 StrictUndefined, UndefinedError, Template, meta, \20 is_undefined, Template20 is_undefined, Template, DictLoader21from jinja2.utils import Cycler2223env = Environment()24
50 unmodified lines
75 assert env.select_template([t]) is t76 assert env.get_or_select_template([t]) is t77 assert env.get_or_select_template(t) is t7879 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>') == '&lt;foo&gt;'93 t = env.from_string('{{ foo }}')94 assert t.render(foo='<foo>') == '<foo>'959697class MetaTestCase(JinjaTestCase):9899 def test_find_undeclared_variables(self):100 ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
117 unmodified lines
modified:jinja2/compiler.py+1 added-1 removed
759 unmodified lines
760 # -- Statement Visitors761762 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)765766 from jinja2.runtime import __all__ as exported767 self.writeline('from __future__ import division')768 self.writeline('from jinja2.runtime import ' + ', '.join(exported))
865 unmodified lines
modified:jinja2/environment.py+7 added-1 removed
158 unmodified lines
159160 `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.167168 .. versionchanged:: 2.4169 `autoescape` can now be a function170171 `loader`172 The template loader for this environment.173174 `cache_size`
916 unmodified lines
modified:jinja2/nodes.py+5 added-2 removed
70 unmodified lines
71 """Holds evaluation time information. Custom attributes can be attached72 to it in extensions.73 """7475 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 = False8182 def save(self):83 return self.__dict__.copy()
791 unmodified lines
modified:jinja2/runtime.py+3 added-3 removed
75 unmodified lines
76 self.__context = context7778 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)8384 def __repr__(self):
28 unmodified lines
113 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 = name120121 # create the initial mapping of blocks. Whenever template inheritance
134 unmodified lines
256257 @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 rv263264
272 unmodified lines