Skip to content
Myr

Merge branch '3.0.x'

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

authored by David Lord · committed by David Lord · parents b2bc7be, 2a48dd8 · Browse files · 12 files+150 added−98 removed
This commit

State

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

Diff stats

12 files+150 added−98 removed

  • tests:+33 added−2 removed
  • other:+117 added−96 removed

12 files+150 added−98 removed

modified:docs/templates.rst+30 added-13 removed
585 unmodified lines
586587Template Objects588~~~~~~~~~~~~~~~~589590.. versionchanged:: 2.4590``extends``, ``include``, and ``import`` can take a template object591instead of the name of a template to load. This could be useful in some592advanced situations, since you can use Python code to load a template593first and pass it in to ``render``.594592If a template object was passed in the template context, you can593extend from that object as well. Assuming the calling code passes594a layout template as `layout_template` to the environment, this595code works::595.. code-block:: python596597 {% extends layout_template %}597 if debug_mode:598 layout = env.get_template("debug_layout.html")599 else:600 layout = env.get_template("layout.html")601599Previously, the `layout_template` variable had to be a string with600the layout template's filename for this to work.602 user_detail = env.get_template("user/detail.html", layout=layout)603604.. code-block:: jinja605606 {% extends layout %}607608Note how ``extends`` is passed the variable with the template object609that was passed to ``render``, instead of a string.610611612HTML Escaping613-------------614615When generating HTML from templates, there's always a risk that a variable will
306 unmodified lines
922923`arguments`924 A tuple of the names of arguments the macro accepts.925917`defaults`918 A tuple of default values.919926`catch_kwargs`927 This is `true` if the macro accepts extra keyword arguments (i.e.: accesses928 the special `kwargs` variable).929
413 unmodified lines
1343 return ``4``. This can also be used to repeat a string multiple times.1344 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.13451346``**``1341 Raise the left operand to the power of the right operand. ``{{ 2**3 }}``1342 would return ``8``.1347 Raise the left operand to the power of the right operand.1348 ``{{ 2**3 }}`` would return ``8``.13491350 Unlike Python, chained pow is evaluated left to right.1351 ``{{ 3**3**3 }}`` is evaluated as ``(3**3)**3`` in Jinja, but would1352 be evaluated as ``3**(3**3)`` in Python. Use parentheses in Jinja1353 to be explicit about what order you want. It is usually preferable1354 to do extended math in Python and pass the results to ``render``1355 rather than doing it in the template.13561357 This behavior may be changed in the future to match Python, if it's1358 possible to introduce an upgrade path.135913601361Comparisons1362~~~~~~~~~~~13631364``==``
541 unmodified lines
modified:src/jinja2/async_utils.py+7 added
42 unmodified lines
4344 return decorator454647_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}484950async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":51 # Avoid a costly call to isawaitable52 if type(value) in _common_primitives:53 return t.cast("V", value)5455 if inspect.isawaitable(value):56 return await t.cast("t.Awaitable[V]", value)5758 return t.cast("V", value)
17 unmodified lines
modified:src/jinja2/debug.py+30 added-50 removed
100 unmodified lines
101 "__file__": filename,102 "__jinja_exception__": exc_value,103 }104 # Raise an exception at the correct line number.105 code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")105 code: CodeType = compile(106 "\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec"107 )108109 # Build a new code object that points to the template file and110 # replaces the location with a block name.109 try:110 location = "template"111 location = "template"112112 if tb is not None:113 function = tb.tb_frame.f_code.co_name113 if tb is not None:114 function = tb.tb_frame.f_code.co_name115115 if function == "root":116 location = "top-level template code"117 elif function.startswith("block_"):118 location = f"block {function[6:]!r}"116 if function == "root":117 location = "top-level template code"118 elif function.startswith("block_"):119 location = f"block {function[6:]!r}"120120 # Collect arguments for the new code object. CodeType only121 # accepts positional arguments, and arguments were inserted in122 # new Python versions.123 code_args = []121 if sys.version_info >= (3, 8):122 code = code.replace(co_name=location)123 else:124 code = CodeType(125 code.co_argcount,126 code.co_kwonlyargcount,127 code.co_nlocals,128 code.co_stacksize,129 code.co_flags,130 code.co_code,131 code.co_consts,132 code.co_names,133 code.co_varnames,134 code.co_filename,135 location,136 code.co_firstlineno,137 code.co_lnotab,138 code.co_freevars,139 code.co_cellvars,140 )141125 for attr in (126 "argcount",127 "posonlyargcount", # Python 3.8128 "kwonlyargcount",129 "nlocals",130 "stacksize",131 "flags",132 "code", # codestring133 "consts", # constants134 "names",135 "varnames",136 ("filename", filename),137 ("name", location),138 "firstlineno",139 "lnotab",140 "freevars",141 "cellvars",142 "linetable", # Python 3.10143 ):144 if isinstance(attr, tuple):145 # Replace with given value.146 code_args.append(attr[1])147 continue148149 try:150 # Copy original value if it exists.151 code_args.append(getattr(code, "co_" + t.cast(str, attr)))152 except AttributeError:153 # Some arguments were added later.154 continue155156 code = CodeType(*code_args)157 except Exception:158 # Some environments such as Google App Engine don't support159 # modifying code objects.160 pass161142 # Execute the new code, which is guaranteed to raise, and return143 # the new traceback without this frame.144 try:145 exec(code, globals, locals)
46 unmodified lines
modified:src/jinja2/environment.py+11 added-24 removed
1112 unmodified lines
1113 return ChainMap(d, self.globals)111411151116class Template:1117 """The central template object. This class represents a compiled template1118 and is used to evaluate it.1117 """A compiled template that can be rendered.11181120 Normally the template object is generated from an :class:`Environment` but1121 it also has a constructor that makes it possible to create a template1122 instance directly using the constructor. It takes the same arguments as1123 the environment constructor but it's not possible to specify a loader.1119 Use the methods on :class:`Environment` to create or load templates.1120 The environment is used to configure how templates are compiled and1121 behave.11221125 Every template object has a few methods and members that are guaranteed1126 to exist. However it's important that a template object should be1127 considered immutable. Modifications on the object are not supported.1123 It is also possible to create a template object directly. This is1124 not usually recommended. The constructor takes most of the same1125 arguments as :class:`Environment`. All templates created with the1126 same environment arguments share the same ephemeral ``Environment``1127 instance behind the scenes.11281129 Template objects created from the constructor rather than an environment1130 do have an `environment` attribute that points to a temporary environment1131 that is probably shared with other templates created with the constructor1132 and compatible settings.11331134 >>> template = Template('Hello {{ name }}!')1135 >>> template.render(name='John Doe') == u'Hello John Doe!'1136 True1137 >>> stream = template.stream(name='John Doe')1138 >>> next(stream) == u'Hello John Doe!'1139 True1140 >>> next(stream)1141 Traceback (most recent call last):1142 ...1143 StopIteration1129 A template object should be considered immutable. Modifications on1130 the object are not supported.1131 """11321133 #: Type of environment to create when creating a template directly1134 #: rather than through an existing environment.
517 unmodified lines
modified:src/jinja2/loaders.py+12 added-4 removed
295 unmodified lines
296 if isinstance(loader, zipimport.zipimporter):297 self._archive = loader.archive298 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore299 template_root = os.path.join(pkgdir, package_path)300 elif spec.submodule_search_locations:301 # This will be one element for regular packages and multiple302 # for namespace packages.303 for root in spec.submodule_search_locations:300 else:301 roots: t.List[str] = []302303 # One element for regular packages, multiple for namespace304 # packages, or None for single module file.305 if spec.submodule_search_locations:306 roots.extend(spec.submodule_search_locations)307 # A single module file, use the parent directory instead.308 elif spec.origin is not None:309 roots.append(os.path.dirname(spec.origin))310311 for root in roots:312 root = os.path.join(root, package_path)313314 if os.path.isdir(root):315 template_root = root
337 unmodified lines
modified:src/jinja2/nativetypes.py+7 added-1 removed
1import typing as t2from ast import literal_eval3from ast import parse4from itertools import chain5from itertools import islice67from . import nodes
25 unmodified lines
33 else:34 raw = "".join([str(v) for v in chain(head, values)])3536 try:36 return literal_eval(raw)37 return literal_eval(38 # In Python 3.10+ ast.literal_eval removes leading spaces/tabs39 # from the given string. For backwards compatibility we need to40 # parse the string ourselves without removing leading spaces/tabs.41 parse(raw, mode="eval")42 )43 except (ValueError, SyntaxError, MemoryError):44 return raw4546
78 unmodified lines
modified:src/jinja2/nodes.py+2 added-3 removed
239 unmodified lines
240 return NotImplemented241242 return tuple(self.iter_fields()) == tuple(other.iter_fields())243244 def __hash__(self) -> int:245 return hash(tuple(self.iter_fields()))244 __hash__ = object.__hash__245246 def __repr__(self) -> str:247 args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)248 return f"{type(self).__name__}({args_str})"
705 unmodified lines
954 operator = "/"955956957class FloorDiv(BinExpr):959 """Divides the left by the right node and truncates conver the958 """Divides the left by the right node and converts the959 result into an integer by truncating.960 """961962 operator = "//"
242 unmodified lines
modified:tests/test_inheritance.py+2 added-2 removed
35 unmodified lines
36{% extends "layout" %}37{% block block1 %}38 {% if false %}39 {% block block2 %}40 this should workd40 this should work41 {% endblock %}42 {% endif %}43{% endblock %}44"""
3 unmodified lines
48{% extends "layout" %}49{% block block1 %}50 {% if false %}51 {% block block2 %}52 this should workd52 this should work53 {% endblock %}54 {% endif %}55{% endblock %}56"""
349 unmodified lines
modified:tests/test_loader.py+22 added
312 unmodified lines
313 assert "test.html" in templates314315316@pytest.fixture()317def package_file_loader(monkeypatch):318 monkeypatch.syspath_prepend(Path(__file__).parent / "res")319 return PackageLoader("__init__")320321322@pytest.mark.parametrize(323 ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]324)325def test_package_file_source(package_file_loader, template, expect):326 source, name, up_to_date = package_file_loader.get_source(None, template)327 assert source.rstrip() == expect328 assert name.endswith(os.path.join(*split_template_path(template)))329 assert up_to_date()330331332def test_package_file_list(package_file_loader):333 templates = package_file_loader.list_templates()334 assert "foo/test.html" in templates335 assert "test.html" in templates336337338@pytest.fixture()339def package_zip_loader(monkeypatch):340 package_zip = (Path(__file__) / ".." / "res" / "package.zip").resolve()341 monkeypatch.syspath_prepend(package_zip)342 return PackageLoader("t_pack")
61 unmodified lines
modified:tests/test_nativetypes.py+6 added
145 unmodified lines
146147def test_spontaneous_env():148 t = NativeTemplate("{{ true }}")149 assert isinstance(t.environment, NativeEnvironment)150151152def test_leading_spaces(env):153 t = env.from_string(" {{ True }}")154 result = t.render()155 assert result == " True"
added:tests/test_nodes.py+3 added
1def test_template_hash(env):2 template = env.parse("hash test")3 hash(template)
modified:CHANGES.rst+18 added-1 removed
4 unmodified lines
56Unreleased789Version 3.0.310-------------1112Released 2021-11-091314- Fix traceback rewriting internals for Python 3.10 and 3.11.15 :issue:`1535`16- Fix how the native environment treats leading and trailing spaces17 when parsing values on Python 3.10. :pr:`1537`18- Improve async performance by avoiding checks for common types.19 :issue:`1514`20- Revert change to ``hash(Node)`` behavior. Nodes are hashed by id21 again :issue:`1521`22- ``PackageLoader`` works when the package is a single module file.23 :issue:`1512`242526Version 3.0.227-------------2829Released 2021-10-04
400 unmodified lines
430 the old behavior where limited assignments to outer scopes was431 possible. For more information and a discussion see :issue:`641`432- Resolved an issue where ``block scoped`` would not take advantage of433 the new scoping rules. In some more exotic cases a variable417 overriden in a local scope would not make it into a block.434 overridden in a local scope would not make it into a block.435- Change the code generation of the ``with`` statement to be in line436 with the new scoping rules. This resolves some unlikely bugs in edge437 cases. This also introduces a new internal ``With`` node that can be438 used by extensions.
483 unmodified lines