Skip to content
Myr

allow optional use of filter based on existence

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Amy · committed by Amy · parent 1c863d0 · 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

4 files+77 added−2 removed

modified:src/jinja2/compiler.py+26 added-2 removed
134 unmodified lines
135 # but they still needs to be kept track of as part of the active context.136 self.loop_frame = False137 self.block_frame = False138139 # 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 = False143144 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 lines
158 """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.161157 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 rv169170 __copy__ = copy171
276 unmodified lines
448 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()468469 def enter_frame(self, frame):470 undefs = []471 for target, (action, param) in frame.symbols.loads.items():
1190 unmodified lines
1662 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 lines
1700 self.write(")")17011702 @optimizeconst1703 def visit_CondExpr(self, node, frame):1704 frame = frame.soft()17051706 def write_expr2():1707 if node.expr2 is not None:1708 return self.visit(node.expr2, frame)1709 self.write(
115 unmodified lines
modified:src/jinja2/runtime.py+1 added
34 unmodified lines
35 "identity",36 "TemplateNotFound",37 "Namespace",38 "Undefined",39 "internalcode",40]414243def identity(x):
887 unmodified lines
modified:tests/test_filters.py+48 added
4 unmodified lines
56from jinja2 import Environment7from jinja2 import Markup8from jinja2 import StrictUndefined9from jinja2 import TemplateRuntimeError10from jinja2 import UndefinedError11from jinja2.exceptions import TemplateAssertionError121314class Magic:15 def __init__(self, value):
759 unmodified lines
775 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."779780 def test_filter_undefined(self, env):781 with pytest.raises(TemplateAssertionError, match="no filter named 'f'"):782 env.from_string("{{ var|f }}")783784 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)789790 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)798799 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)806807 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)816817 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"821822 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 lines
38 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`444546Version 2.11.347--------------
780 unmodified lines