Skip to content
Myr

add 'is filter' and 'is test' tests

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

This required allowing tests to be decorated with '@environmentfilter'. Tests are essentially the same as filters now, the node, compiler, and environment have been refactored to extract common behavior.

authored by David Lord · committed by David Lord · parent af5d80e · Browse files · 8 files+342 added−175 removed
This commit

State

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

Diff stats

8 files+342 added−175 removed

  • tests:+31 added−6 removed
  • other:+311 added−169 removed

8 files+342 added−175 removed

modified:docs/api.rst+95 added-72 removed
664 unmodified lines
665666Custom Filters667--------------668669Custom filters are just regular Python functions that take the left side of670the filter as first argument and the arguments passed to the filter as671extra arguments or keyword arguments.669Filters are Python functions that take the value to the left of the670filter as the first argument and produce a new value. Arguments passed671to the filter are passed after the value.672673For example in the filter ``{{ 42|myfilter(23) }}`` the function would be674called with ``myfilter(42, 23)``. Here for example a simple filter that can675be applied to datetime objects to format them::673For example, the filter ``{{ 42|myfilter(23) }}`` is called behind the674scenes as ``myfilter(42, 23)``.675677 def datetimeformat(value, format='%H:%M / %d-%m-%Y'):678 return value.strftime(format)676Jinja comes with some :ref:`built-in filters <builtin-filters>`. To use677a custom filter, write a function that takes at least a ``value``678argument, then register it in :attr:`Environment.filters`.679680You can register it on the template environment by updating the681:attr:`~Environment.filters` dict on the environment::680Here's a filter that formats datetime objects:681683 environment.filters['datetimeformat'] = datetimeformat682.. code-block:: python683685Inside the template it can then be used as follows:684 def datetime_format(value, format="%H:%M %d-%m-%y"):685 return value.strftime(format)686687 environment.filters["datetime_format"] = datetime_format688689Now it can be used in templates:690691.. sourcecode:: jinja692689 written on: {{ article.pub_date|datetimeformat }}690 publication date: {{ article.pub_date|datetimeformat('%d-%m-%Y') }}693 {{ article.pub_date|datetimeformat }}694 {{ article.pub_date|datetimeformat("%B %Y") }}695692Filters can also be passed the current template context or environment. This693is useful if a filter wants to return an undefined value or check the current694:attr:`~Environment.autoescape` setting. For this purpose three decorators695exist: :func:`environmentfilter`, :func:`contextfilter` and696:func:`evalcontextfilter`.696Some decorators are available to tell Jinja to pass extra information to697the filter. The object is passed as the first argument, making the value698being filtered the second argument.699698Here a small example filter that breaks a text into HTML line breaks and699paragraphs and marks the return value as safe HTML string if autoescaping is700enabled::700- :func:`environmentfilter` passes the :class:`Environment`.701- :func:`evalcontextfilter` passes the :ref:`eval-context`.702- :func:`contextfilter` passes the current703 :class:`~jinja2.runtime.Context`.704702 import re703 from jinja2 import evalcontextfilter, Markup, escape705Here's a filter that converts line breaks into HTML ``<br>`` and ``<p>``706tags. It uses the eval context to check if autoescape is currently707enabled before escaping the input and marking the output safe.708705 _paragraph_re = re.compile(r"(?:\r\n|\r(?!\n)|\n){2,}")709.. code-block:: python710711 import re712 from jinja2 import evalcontextfilter713 from markupsafe import Markup, escape714715 @evalcontextfilter716 def nl2br(eval_ctx, value):717 br = "<br>\n"718719 if eval_ctx.autoescape:720 value = escape(value)721 br = Markup(br)722723 result = "\n\n".join(710 f"<p>{p.replace('\n', Markup('<br>\n'))}</p>"711 for p in _paragraph_re.split(escape(value))724 f"<p>{br.join(p.splitlines())}<\p>"725 for p in re.split(r"(?:\r\n|\r(?!\n)|\n){2,}", value)726 )713 if eval_ctx.autoescape:714 result = Markup(result)715 return result727 return Markup(result) if autoescape else result728717Context filters work the same just that the first argument is the current718active :class:`Context` rather than the environment.729730.. _writing-tests:731732Custom Tests733------------734735Test are Python functions that take the value to the left of the test as736the first argument, and return ``True`` or ``False``. Arguments passed737to the test are passed after the value.738739For example, the test ``{{ 42 is even }}`` is called behind the scenes740as ``is_even(42)``.741742Jinja comes with some :ref:`built-in tests <builtin-tests>`. To use a743custom tests, write a function that takes at least a ``value`` argument,744then register it in :attr:`Environment.tests`.745746Here's a test that checks if a value is a prime number:747748.. code-block:: python749750 import math751752 def is_prime(n):753 if n == 2:754 return True755756 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):757 if n % i == 0:758 return False759760 return True761762 environment.tests["prime"] = is_prime763764Now it can be used in templates:765766.. sourcecode:: jinja767768 {% if value is prime %}769 {{ value }} is a prime number770 {% else %}771 {{ value }} is not a prime number772 {% endif %}773774Some decorators are available to tell Jinja to pass extra information to775the filter. The object is passed as the first argument, making the value776being filtered the second argument.777778- :func:`environmentfunction` passes the :class:`Environment`.779- :func:`evalcontextfunction` passes the :ref:`eval-context`.780- :func:`contextfunction` passes the current781 :class:`~jinja2.runtime.Context`.782783784.. _eval-context:785786Evaluation Context787------------------
54 unmodified lines
842 `True` if the compiler cannot evaluate some expressions at compile843 time. At runtime this should always be `False`.844845783.. _writing-tests:784785Custom Tests786------------787788Tests work like filters just that there is no way for a test to get access789to the environment or context and that they can't be chained. The return790value of a test should be `True` or `False`. The purpose of a test is to791give the template designers the possibility to perform type and conformability792checks.793794Here a simple test that checks if a variable is a prime number::795796 import math797798 def is_prime(n):799 if n == 2:800 return True801 for i in range(2, int(math.ceil(math.sqrt(n))) + 1):802 if n % i == 0:803 return False804 return True805806807You can register it on the template environment by updating the808:attr:`~Environment.tests` dict on the environment::809810 environment.tests['prime'] = is_prime811812A template designer can then use the test like this:813814.. sourcecode:: jinja815816 {% if 42 is prime %}817 42 is a prime number818 {% else %}819 42 is not a prime number820 {% endif %}821822846.. _global-namespace:847848The Global Namespace849--------------------
85 unmodified lines
modified:src/jinja2/compiler.py+66 added-29 removed
1"""Compiles nodes from the parser into Python code."""2import typing as t3from collections import namedtuple4from contextlib import contextmanager5from functools import update_wrapper6from io import StringIO7from itertools import chain8from keyword import iskeyword as is_python_keyword
431 unmodified lines
440 self.write(", **")441 self.visit(node.dyn_kwargs, frame)442443 def pull_dependencies(self, nodes):443 """Pull all the dependencies."""444 """Find all filter and test names used in the template and445 assign them to variables in the compiled namespace. Checking446 that the names are registered with the environment is done when447 compiling the Filter and Test nodes. If the node is in an If or448 CondExpr node, the check is done at runtime instead.449450 .. versionchanged:: 3.0451 Filters and tests in If and CondExpr nodes are checked at452 runtime instead of compile time.453 """454 visitor = DependencyFinderVisitor()455456 for node in nodes:457 visitor.visit(node)458459 for dependency in "filters", "tests":460 mapping = getattr(self, dependency)461462 for name in getattr(visitor, dependency):463 if name not in mapping:464 mapping[name] = self.temporary_identifier()465466 # add check during runtime that dependencies used inside of executed467 # blocks are defined, as this step may be skipped during compile time468 self.writeline("try:")469 self.indent()
4 unmodified lines
474 self.writeline("@internalcode")475 self.writeline(f"def {mapping[name]}(*unused):")476 self.indent()477 self.writeline(464 f'raise TemplateRuntimeError("no filter named {name!r} found")'478 f'raise TemplateRuntimeError("No {dependency[:-1]}'479 f' named {name!r} found.")'480 )481 self.outdent()482 self.outdent()483
1187 unmodified lines
1671 if node.step is not None:1672 self.write(":")1673 self.visit(node.step, frame)16741660 @optimizeconst1661 def visit_Filter(self, node, frame):1675 @contextmanager1676 def _filter_test_common(self, node, frame, is_filter):1677 if is_filter:1678 compiler_map = self.filters1679 env_map = self.environment.filters1680 type_name = mark_name = "filter"1681 else:1682 compiler_map = self.tests1683 env_map = self.environment.tests1684 type_name = "test"1685 # Filters use "contextfilter", tests and calls use "contextfunction".1686 mark_name = "function"16871688 if self.environment.is_async:1689 self.write("await auto_await(")16901664 self.write(self.filters[node.name] + "(")1665 func = self.environment.filters.get(node.name)1691 self.write(compiler_map[node.name] + "(")1692 func = env_map.get(node.name)16931694 # When inside an If or CondExpr frame, allow the filter to be1695 # undefined at compile time and only raise an error if it's1696 # actually called at runtime. See pull_dependencies.1697 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:1698 self.fail(f"No {type_name} named {node.name!r}.", node.lineno)16991700 if getattr(func, f"context{mark_name}", False) is True:1701 self.write("context, ")1670 elif getattr(func, "evalcontextfilter", False) is True:1702 elif getattr(func, f"evalcontext{mark_name}", False) is True:1703 self.write("context.eval_ctx, ")1672 elif getattr(func, "environmentfilter", False) is True:1704 elif getattr(func, f"environment{mark_name}", False) is True:1705 self.write("environment, ")17061675 # if the filter node is None we are inside a filter block1676 # and want to write to the current buffer1677 if node.node is not None:1678 self.visit(node.node, frame)1679 elif frame.eval_ctx.volatile:1680 self.write(1681 f"(Markup(concat({frame.buffer}))"1682 f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1683 )1684 elif frame.eval_ctx.autoescape:1685 self.write(f"Markup(concat({frame.buffer}))")1686 else:1687 self.write(f"concat({frame.buffer})")1707 # Back to the visitor function to handle visiting the target of1708 # the filter or test.1709 yield17101711 self.signature(node, frame)1712 self.write(")")17131714 if self.environment.is_async:1715 self.write(")")17161717 @optimizeconst1718 def visit_Filter(self, node, frame):1719 with self._filter_test_common(node, frame, True):1720 # if the filter node is None we are inside a filter block1721 # and want to write to the current buffer1722 if node.node is not None:1723 self.visit(node.node, frame)1724 elif frame.eval_ctx.volatile:1725 self.write(1726 f"(Markup(concat({frame.buffer}))"1727 f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1728 )1729 elif frame.eval_ctx.autoescape:1730 self.write(f"Markup(concat({frame.buffer}))")1731 else:1732 self.write(f"concat({frame.buffer})")17331734 @optimizeconst1735 def visit_Test(self, node, frame):1695 self.write(self.tests[node.name] + "(")1696 if node.name not in self.environment.tests:1697 self.fail(f"no test named {node.name!r}", node.lineno)1698 self.visit(node.node, frame)1699 self.signature(node, frame)1700 self.write(")")1736 with self._filter_test_common(node, frame, False):1737 self.visit(node.node, frame)17381739 @optimizeconst1740 def visit_CondExpr(self, node, frame):1741 frame = frame.soft()
120 unmodified lines
modified:src/jinja2/environment.py+62 added-33 removed
100 unmodified lines
101 result[extension.identifier] = extension(environment)102 return result103104105def fail_for_missing_callable(thing, name):106 msg = f"no {thing} named {name!r}"107108 if isinstance(name, Undefined):109 try:110 name._fail_with_undefined_error()111 except Exception as e:112 msg = f"{msg} ({e}; did you forget to quote the callable name?)"113 raise TemplateRuntimeError(msg)114115105def _environment_sanity_check(environment):106 """Perform a sanity check on the environment."""107 assert issubclass(108 environment.undefined, Undefined
349 unmodified lines
458 return obj[attribute]459 except (TypeError, LookupError, AttributeError):460 return self.undefined(obj=obj, name=attribute)461473 def call_filter(474 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None462 def _filter_test_common(463 self, name, value, args, kwargs, context, eval_ctx, is_filter464 ):476 """Invokes a filter on a value the same way the compiler does.465 if is_filter:466 env_map = self.filters467 type_name = mark_name = "filter"468 else:469 env_map = self.tests470 type_name = "test"471 # Filters use "contextfilter", tests and calls use "contextfunction".472 mark_name = "function"473478 This might return a coroutine if the filter is running from an479 environment in async mode and the filter supports async480 execution. It's your responsibility to await this if needed.474 func = env_map.get(name)475482 .. versionadded:: 2.7483 """484 func = self.filters.get(name)476 if func is None:486 fail_for_missing_callable("filter", name)487 args = [value] + list(args or ())488 if getattr(func, "contextfilter", False) is True:477 msg = f"No {type_name} named {name!r}."478479 if isinstance(name, Undefined):480 try:481 name._fail_with_undefined_error()482 except Exception as e:483 msg = f"{msg} ({e}; did you forget to quote the callable name?)"484485 raise TemplateRuntimeError(msg)486487 args = [value, *(args if args is not None else ())]488 kwargs = kwargs if kwargs is not None else {}489490 if getattr(func, f"context{mark_name}", False) is True:491 if context is None:492 raise TemplateRuntimeError(491 "Attempted to invoke context filter without context"493 f"Attempted to invoke a context {type_name} without context."494 )495496 args.insert(0, context)494 elif getattr(func, "evalcontextfilter", False) is True:497 elif getattr(func, f"evalcontext{mark_name}", False) is True:498 if eval_ctx is None:499 if context is not None:500 eval_ctx = context.eval_ctx501 else:502 eval_ctx = EvalContext(self)503504 args.insert(0, eval_ctx)501 elif getattr(func, "environmentfilter", False) is True:505 elif getattr(func, f"environment{mark_name}", False) is True:506 args.insert(0, self)503 return func(*args, **(kwargs or {}))507505 def call_test(self, name, value, args=None, kwargs=None):506 """Invokes a test on a value the same way the compiler does it.508 return func(*args, **kwargs)509510 def call_filter(511 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None512 ):513 """Invoke a filter on a value the same way the compiler does.514515 This might return a coroutine if the filter is running from an516 environment in async mode and the filter supports async517 execution. It's your responsibility to await this if needed.518519 .. versionadded:: 2.7520 """510 func = self.tests.get(name)511 if func is None:512 fail_for_missing_callable("test", name)513 return func(value, *(args or ()), **(kwargs or {}))521 return self._filter_test_common(522 name, value, args, kwargs, context, eval_ctx, True523 )524525 def call_test(526 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None527 ):528 """Invoke a test on a value the same way the compiler does.529530 This might return a coroutine if the test is running from an531 environment in async mode and the test supports async execution.532 It's your responsibility to await this if needed.533534 .. versionchanged:: 3.0535 Tests support ``@contextfunction``, etc. decorators. Added536 the ``context`` and ``eval_ctx`` parameters.537538 .. versionadded:: 2.7539 """540 return self._filter_test_common(541 name, value, args, kwargs, context, eval_ctx, False542 )543544 @internalcode545 def parse(self, source, name=None, filename=None):546 """Parse the sourcecode and return the abstract syntax tree. This547 tree of nodes is used by the compiler to convert the template into
865 unmodified lines
modified:src/jinja2/nodes.py+40 added-35 removed
631 unmodified lines
632633 return args, kwargs634635636class Filter(Expr):637 """This node applies a filter on an expression. `name` is the name of638 the filter, the rest of the fields are the same as for :class:`Call`.639640 If the `node` of a filter is `None` the contents of the last buffer are641 filtered. Buffers are created by macros and filter blocks.642 """643636class _FilterTestCommon(Expr):637 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")638 abstract = True639 _is_filter = True640641 def as_const(self, eval_ctx=None):642 eval_ctx = get_eval_context(self, eval_ctx)643649 if eval_ctx.volatile or self.node is None:644 if eval_ctx.volatile:645 raise Impossible()646652 filter_ = self.environment.filters.get(self.name)647 if self._is_filter:648 env_map = eval_ctx.environment.filters649 mark_name = "filter"650 else:651 env_map = eval_ctx.environment.tests652 # Filters use "contextfilter", tests and calls use "contextfunction".653 mark_name = "function"654654 if filter_ is None or getattr(filter_, "contextfilter", False) is True:655 func = env_map.get(self.name)656657 if func is None or getattr(func, f"context{mark_name}", False) is True:658 raise Impossible()659657 # We cannot constant handle async filters, so we need to make658 # sure to not go down this path. Account for both sync/async and659 # pure-async filters.660 if eval_ctx.environment.is_async and (661 getattr(filter_, "asyncfiltervariant", False)662 or inspect.iscoroutinefunction(filter_)661 getattr(func, f"async{mark_name}variant", False)662 or inspect.iscoroutinefunction(func)663 ):664 raise Impossible()665666 args, kwargs = args_as_const(self, eval_ctx)667 args.insert(0, self.node.as_const(eval_ctx))668669 if getattr(filter_, "evalcontextfilter", False) is True:669 if getattr(func, f"evalcontext{mark_name}", False) is True:670 args.insert(0, eval_ctx)671 elif getattr(filter_, "environmentfilter", False) is True:672 args.insert(0, self.environment)671 elif getattr(func, f"environment{mark_name}", False) is True:672 args.insert(0, eval_ctx.environment)673674 try:675 return filter_(*args, **kwargs)675 return func(*args, **kwargs)676 except Exception:677 raise Impossible()678679680class Test(Expr):681 """Applies a test on an expression. `name` is the name of the test, the682 rest of the fields are the same as for :class:`Call`.680class Filter(_FilterTestCommon):681 """Apply a filter to an expression. ``name`` is the name of the682 filter, the other fields are the same as :class:`Call`.683684 If ``node`` is ``None``, the filter is being used in a filter block685 and is applied to the content of the block.686 """687685 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")686688 def as_const(self, eval_ctx=None):688 test = self.environment.tests.get(self.name)689690 if test is None:689 if self.node is None:690 raise Impossible()691693 eval_ctx = get_eval_context(self, eval_ctx)694 args, kwargs = args_as_const(self, eval_ctx)695 args.insert(0, self.node.as_const(eval_ctx))692 return super().as_const(eval_ctx=eval_ctx)693697 try:698 return test(*args, **kwargs)699 except Exception:700 raise Impossible()694695class Test(_FilterTestCommon):696 """Apply a test to an expression. ``name`` is the name of the test,697 the other field are the same as :class:`Call`.698699 .. versionchanged:: 3.0700 ``as_const`` shares the same logic for filters and tests. Tests701 check for volatile, async, and ``@contextfunction`` etc.702 decorators.703 """704705 _is_filter = False706707708class Call(Expr):709 """Calls an expression. `args` is a list of arguments, `kwargs` a list710 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`711 and `dyn_kwargs` has to be either `None` or a node that is used as
355 unmodified lines
modified:src/jinja2/tests.py+43 added
3 unmodified lines
4from collections import abc5from numbers import Number67from .runtime import Undefined8from .utils import environmentfunction910number_re = re.compile(r"^-?\d+(\.\d+)?$")11regex_type = type(number_re)12test_callable = callable
35 unmodified lines
48 """Like :func:`defined` but the other way round."""49 return isinstance(value, Undefined)505152@environmentfunction53def test_filter(env, value):54 """Check if a filter exists by name. Useful if a filter may be55 optionally available.5657 .. code-block:: jinja5859 {% if 'markdown' is filter %}60 {{ value | markdown }}61 {% else %}62 {{ value }}63 {% endif %}6465 .. versionadded:: 3.066 """67 return value in env.filters686970@environmentfunction71def test_test(env, value):72 """Check if a test exists by name. Useful if a test may be73 optionally available.7475 .. code-block:: jinja7677 {% if 'loud' is test %}78 {% if value is loud %}79 {{ value|upper }}80 {% else %}81 {{ value|lower }}82 {% endif %}83 {% else %}84 {{ value }}85 {% endif %}8687 .. versionadded:: 3.088 """89 return value in env.tests909192def test_none(value):93 """Return true if the variable is none."""94 return value is None95
120 unmodified lines
216 "even": test_even,217 "divisibleby": test_divisibleby,218 "defined": test_defined,219 "undefined": test_undefined,220 "filter": test_filter,221 "test": test_test,222 "none": test_none,223 "boolean": test_boolean,224 "false": test_false,225 "true": test_true,
29 unmodified lines
modified:tests/test_filters.py+6 added-6 removed
776 unmodified lines
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'"):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'"):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'"):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'"):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(
1 unmodified line
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'"):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'"):822 with pytest.raises(TemplateRuntimeError, match="No filter named 'f'"):823 t1.render(x=42)824 t2.render(x=42)
modified:tests/test_tests.py+25 added
1import pytest23from jinja2 import Environment4from jinja2 import Markup5from jinja2 import TemplateAssertionError6from jinja2 import TemplateRuntimeError789class MyDict(dict):10 pass
196 unmodified lines
207 '{{ "foo" is in {"foo": 1}}}|'208 '{{ "baz" is in {"bar": 1}}}'209 )210 assert tmpl.render() == "True|True|False|True|False|True|False|True|False"211212213def test_name_undefined(env):214 with pytest.raises(TemplateAssertionError, match="No test named 'f'"):215 env.from_string("{{ x is f }}")216217218def test_name_undefined_in_if(env):219 t = env.from_string("{% if x is defined %}{{ x is f }}{% endif %}")220 assert t.render() == ""221222 with pytest.raises(TemplateRuntimeError, match="No test named 'f'"):223 t.render(x=1)224225226def test_is_filter(env):227 assert env.call_test("filter", "title")228 assert not env.call_test("filter", "bad-name")229230231def test_is_test(env):232 assert env.call_test("test", "number")233 assert not env.call_test("test", "bad-name")
modified:CHANGES.rst+5 added
39 unmodified lines
40 ``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- Add ``is filter`` and ``is test`` tests to test if a name is a45 registered filter or test. This allows checking if a filter is46 available in a template before using it. Test functions can be47 decorated with ``@environmentfunction``, ``@evalcontextfunction``,48 or ``@contextfunction``. :issue:`842`, :pr:`1248`495051Version 2.11.352--------------
780 unmodified lines