Merge pull request #1248 from MLH-Fellowship/test-for-filter
Before adoption: this commit came in with the history the project adopted, so no landing records it.
allow optional use of a filter based on its existence
authored by David Lord · committed by GitHub · parents 1c863d0, ebf0e2d · Browse files · 4 files·+77 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+77 added−2 removed
- tests:+48 added−0 removed
- other:+29 added−2 removed
Provenance
- Commit
af5d80e- Tree
32bc5e7- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
1c863d0- Parent 2
ebf0e2d
4 files changed+77 added−2 removed
modified:src/jinja2/compiler.py+26 added-2 removed
134 unmodified lines135 # but they still needs to be kept track of as part of the active context.136 self.loop_frame = False137 self.block_frame = False138 139+ # track whether the frame is being used in an if-statement or conditional140+ # expression as it determines which errors should be raised during runtime141+ # or compile time.142+ self.soft_frame = False143+144 def copy(self):145 """Create a copy of the current one."""146 rv = object.__new__(self.__class__)147 rv.__dict__.update(self.__dict__)10 unmodified lines158 """Return a soft frame. A soft frame may not be modified as159 standalone thing as it shares the resources with the frame it160 was created of, but it's not a rootlevel frame any longer.161 157- This is only used to implement if-statements.162+ This is only used to implement if-statements and conditional163+ expressions.164 """165 rv = self.copy()166 rv.rootlevel = False167+ rv.soft_frame = True168 return rv169 170 __copy__ = copy171 276 unmodified lines448 mapping = getattr(self, dependency)449 for name in getattr(visitor, dependency):450 if name not in mapping:451 mapping[name] = self.temporary_identifier()452+ # add check during runtime that dependencies used inside of executed453+ # blocks are defined, as this step may be skipped during compile time454+ self.writeline("try:")455+ self.indent()456 self.writeline(f"{mapping[name]} = environment.{dependency}[{name!r}]")457+ self.outdent()458+ self.writeline("except KeyError:")459+ self.indent()460+ self.writeline("@internalcode")461+ self.writeline(f"def {mapping[name]}(*unused):")462+ self.indent()463+ self.writeline(464+ f'raise TemplateRuntimeError("no filter named {name!r} found")'465+ )466+ self.outdent()467+ self.outdent()468 469 def enter_frame(self, frame):470 undefs = []471 for target, (action, param) in frame.symbols.loads.items():1190 unmodified lines1662 if self.environment.is_async:1663 self.write("await auto_await(")1664 self.write(self.filters[node.name] + "(")1665 func = self.environment.filters.get(node.name)1644- if func is None:1666+ if func is None and not frame.soft_frame:1667 self.fail(f"no filter named {node.name!r}", node.lineno)1668 if getattr(func, "contextfilter", False) is True:1669 self.write("context, ")1670 elif getattr(func, "evalcontextfilter", False) is True:29 unmodified lines1700 self.write(")")1701 1702 @optimizeconst1703 def visit_CondExpr(self, node, frame):1704+ frame = frame.soft()1705+1706 def write_expr2():1707 if node.expr2 is not None:1708 return self.visit(node.expr2, frame)1709 self.write(115 unmodified linesmodified:src/jinja2/runtime.py+1 added
34 unmodified lines35 "identity",36 "TemplateNotFound",37 "Namespace",38 "Undefined",39+ "internalcode",40 ]41 42 43 def identity(x):887 unmodified linesmodified:tests/test_filters.py+48 added
4 unmodified lines5 6 from jinja2 import Environment7 from jinja2 import Markup8 from jinja2 import StrictUndefined9+from jinja2 import TemplateRuntimeError10 from jinja2 import UndefinedError11+from jinja2.exceptions import TemplateAssertionError12 13 14 class Magic:15 def __init__(self, value):759 unmodified lines775 env.newline_sequence = "\n"776 t = env.from_string("{{ s|wordwrap(20) }}")777 result = t.render(s="Hello!\nThis is Jinja saying something.")778 assert result == "Hello!\nThis is Jinja saying\nsomething."779+780+ def test_filter_undefined(self, env):781+ with pytest.raises(TemplateAssertionError, match="no filter named 'f'"):782+ env.from_string("{{ var|f }}")783+784+ def test_filter_undefined_in_if(self, env):785+ t = env.from_string("{%- if x is defined -%}{{ x|f }}{%- else -%}x{% endif %}")786+ assert t.render() == "x"787+ with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):788+ t.render(x=42)789+790+ def test_filter_undefined_in_elif(self, env):791+ t = env.from_string(792+ "{%- if x is defined -%}{{ x }}{%- elif y is defined -%}"793+ "{{ y|f }}{%- else -%}foo{%- endif -%}"794+ )795+ assert t.render() == "foo"796+ with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):797+ t.render(y=42)798+799+ def test_filter_undefined_in_else(self, env):800+ t = env.from_string(801+ "{%- if x is not defined -%}foo{%- else -%}{{ x|f }}{%- endif -%}"802+ )803+ assert t.render() == "foo"804+ with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):805+ t.render(x=42)806+807+ def test_filter_undefined_in_nested_if(self, env):808+ t = env.from_string(809+ "{%- if x is not defined -%}foo{%- else -%}{%- if y "810+ "is defined -%}{{ y|f }}{%- endif -%}{{ x }}{%- endif -%}"811+ )812+ assert t.render() == "foo"813+ assert t.render(x=42) == "42"814+ with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):815+ t.render(x=24, y=42)816+817+ def test_filter_undefined_in_condexpr(self, env):818+ t1 = env.from_string("{{ x|f if x is defined else 'foo' }}")819+ t2 = env.from_string("{{ 'foo' if x is not defined else x|f }}")820+ assert t1.render() == t2.render() == "foo"821+822+ with pytest.raises(TemplateRuntimeError, match="no filter named 'f'"):823+ t1.render(x=42)824+ t2.render(x=42)modified:CHANGES.rst+2 added
37 unmodified lines38 variables. :issue:`1088`39 - Update the template globals when calling40 ``Environment.get_template(globals=...)`` even if the template was41 already loaded. :issue:`295`42+- Do not raise an error for undefined filters in unexecuted43+ if-statements and conditional expressions. :issue:`842`44 45 46 Version 2.11.347 --------------780 unmodified lines