Use separate undefined object for CondExpr
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Adrian Moennich · committed by Adrian Moennich · parent 464e493 · Browse files · 5 files·+34 added−6 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+34 added−6 removed
- tests:+9 added−0 removed
- other:+25 added−6 removed
Provenance
- Commit
c4d3996- Tree
870f474- Author
Adrian Moennich <adrian@planetcoding.net>- Committer
Adrian Moennich <adrian@planetcoding.net>- Parent
464e493
5 files changed+34 added−6 removed
modified:docs/templates.rst+2 added-1 removed
1353 unmodified lines1354 The general syntax is ``<do something> if <something is true> else <do1355 something else>``.1356 1357 The `else` part is optional. If not provided, the else block implicitly1358-evaluates into an undefined object:1358+evaluates into an undefined object (using the environment's undefined object1359+specified in ``cond_expr_undefined``):1360 1361 .. sourcecode:: jinja1362 1363 {{ "[{}]".format(page.title) if page.title }}399 unmodified linesmodified:jinja2/compiler.py+2 added-1 removed
607 unmodified lines608 through a dead branch.609 """610 self.writeline('resolve = context.resolve_or_missing')611 self.writeline('undefined = environment.undefined')612+ self.writeline('cond_expr_undefined = environment.cond_expr_undefined')613 self.writeline('if 0: yield None')614 615 def push_parameter_definitions(self, frame):616 """Pushes all parameter targets from the given frame into a local1006 unmodified lines1623 def visit_CondExpr(self, node, frame):1624 def write_expr2():1625 if node.expr2 is not None:1626 return self.visit(node.expr2, frame)1626- self.write('undefined(%r)' % ('the inline if-'1627+ self.write('cond_expr_undefined(%r)' % ('the inline if-'1628 'expression on %s evaluated to false and '1629 'no else section was defined.' % self.position(node)))1630 1631 self.write('(')100 unmodified linesmodified:jinja2/environment.py+17 added-4 removed
99 unmodified lines100 def _environment_sanity_check(environment):101 """Perform a sanity check on the environment."""102 assert issubclass(environment.undefined, Undefined), 'undefined must ' \103 'be a subclass of undefined because filters depend on it.'104+ assert issubclass(environment.cond_expr_undefined, Undefined), \105+ 'cond_expr_undefined must be a subclass of undefined because filters ' \106+ 'depend on it.'107 assert environment.block_start_string != \108 environment.variable_start_string != \109 environment.comment_start_string, 'block, variable and comment ' \110 'start strings must be different'74 unmodified lines185 `undefined`186 :class:`Undefined` or a subclass of it that is used to represent187 undefined values in the template.188 189+ `cond_expr_undefined`190+ :class:`Undefined` or a subclass of it that is used to represent191+ undefined values in the template for conditional expressions that192+ have no ``else`` part. This is usually useful when using a more193+ strict undefined class without wanting to break the short version194+ of conditional expressions.195+196 `finalize`197 A callable that can be used to process the result of a variable198 expression before it is output. For example one can convert199 ``None`` implicitly into an empty string here.92 unmodified lines292 loader=None,293 cache_size=400,294 auto_reload=True,295 bytecode_cache=None,286- enable_async=False):296+ enable_async=False,297+ cond_expr_undefined=Undefined):298 # !!Important notice!!299 # The constructor accepts quite a few arguments that should be300 # passed by keyword rather than position. However it's important to301 # not change the order of arguments because it's used at least19 unmodified lines321 self.keep_trailing_newline = keep_trailing_newline322 323 # runtime information324 self.undefined = undefined325+ self.cond_expr_undefined = cond_expr_undefined326 self.optimized = optimized327 self.finalize = finalize328 self.autoescape = autoescape329 44 unmodified lines374 trim_blocks=missing, lstrip_blocks=missing,375 extensions=missing, optimized=missing,376 undefined=missing, finalize=missing, autoescape=missing,377 loader=missing, cache_size=missing, auto_reload=missing,366- bytecode_cache=missing):378+ bytecode_cache=missing, cond_expr_undefined=missing):379 """Create a new overlay environment that shares all the data with the380 current environment except for cache and the overridden attributes.381 Extensions cannot be removed for an overlayed environment. An overlayed382 environment automatically gets all the extensions of the environment it564 unmodified lines947 optimized=True,948 undefined=Undefined,949 finalize=None,950 autoescape=False,939- enable_async=False):951+ enable_async=False,952+ cond_expr_undefined=Undefined):953 env = get_spontaneous_environment(954 block_start_string, block_end_string, variable_start_string,955 variable_end_string, comment_start_string, comment_end_string,956 line_statement_prefix, line_comment_prefix, trim_blocks,957 lstrip_blocks, newline_sequence, keep_trailing_newline,958 frozenset(extensions), optimized, undefined, finalize, autoescape,946- None, 0, False, None, enable_async)959+ None, 0, False, None, enable_async, cond_expr_undefined)960 return env.from_string(source, template_class=cls)961 962 @classmethod963 def from_code(cls, environment, code, globals, uptodate=None):328 unmodified linesmodified:tests/test_api.py+9 added
366 unmodified lines367 .render() == 'default'368 with pytest.raises(AttributeError):369 getattr(StrictUndefined, '__slots__')370 371+ def test_cond_expr_undefined(self):372+ env = Environment(cond_expr_undefined=StrictUndefined)373+ env2 = Environment(undefined=StrictUndefined)374+ pytest.raises(UndefinedError,375+ env.from_string('{{ "foo" if false }}').render)376+ assert env.from_string('{{ ("foo" if false) is defined }}').render() == 'False'377+ assert env2.from_string('{{ "foo" if false }}').render() == ''378+ assert env2.from_string('{{ ("foo" if false) is defined }}').render() == 'False'379+380 def test_indexing_gives_undefined(self):381 t = Template("{{ var[42].foo }}")382 pytest.raises(UndefinedError, t.render, var=0)383 40 unmodified linesmodified:CHANGES.rst+4 added
37 unmodified lines38 output of expressions (constant or not), not static template data.39 :issue:`63`40 - When providing multiple paths to ``FileSystemLoader``, a template41 can have the same name as a directory. :issue:`821`42+- Make the undefined object returned by ``{{ 'foo' if bar }}`` configurable,43+ and default to standard ``Undefined`` regardless of what is specified as44+ the environment's ``undefined`` object as doing so is not compatible with45+ ``StrictUndefined``. :issue:`710`, :pr:`1079`46 47 48 Version 2.10.349 --------------629 unmodified lines