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
Provenance
- Commit
a42b291- Tree
48c8833- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
b2bc7be- Parent 2
2a48dd8
12 files changed+150 added−98 removed
modified:docs/templates.rst+30 added-13 removed
585 unmodified lines586 587 Template Objects588 ~~~~~~~~~~~~~~~~589 590-.. versionchanged:: 2.4590+``extends``, ``include``, and ``import`` can take a template object591+instead of the name of a template to load. This could be useful in some592+advanced situations, since you can use Python code to load a template593+first and pass it in to ``render``.594 592-If a template object was passed in the template context, you can593-extend from that object as well. Assuming the calling code passes594-a layout template as `layout_template` to the environment, this595-code works::595+.. code-block:: python596 597- {% extends layout_template %}597+ if debug_mode:598+ layout = env.get_template("debug_layout.html")599+ else:600+ layout = env.get_template("layout.html")601 599-Previously, the `layout_template` variable had to be a string with600-the layout template's filename for this to work.602+ user_detail = env.get_template("user/detail.html", layout=layout)603 604+.. code-block:: jinja605 606+ {% extends layout %}607+608+Note how ``extends`` is passed the variable with the template object609+that was passed to ``render``, instead of a string.610+611+612 HTML Escaping613 -------------614 615 When generating HTML from templates, there's always a risk that a variable will306 unmodified lines922 923 `arguments`924 A tuple of the names of arguments the macro accepts.925 917-`defaults`918- A tuple of default values.919-926 `catch_kwargs`927 This is `true` if the macro accepts extra keyword arguments (i.e.: accesses928 the special `kwargs` variable).929 413 unmodified lines1343 return ``4``. This can also be used to repeat a string multiple times.1344 ``{{ '=' * 80 }}`` would print a bar of 80 equal signs.1345 1346 ``**``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``.1349 1350+ 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.1356+1357+ This behavior may be changed in the future to match Python, if it's1358+ possible to introduce an upgrade path.1359+1360+1361 Comparisons1362 ~~~~~~~~~~~1363 1364 ``==``541 unmodified linesmodified:src/jinja2/async_utils.py+7 added
42 unmodified lines43 44 return decorator45 46 47+_common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}48+49+50 async 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)54+55 if inspect.isawaitable(value):56 return await t.cast("t.Awaitable[V]", value)57 58 return t.cast("V", value)17 unmodified linesmodified:src/jinja2/debug.py+30 added-50 removed
100 unmodified lines101 "__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+ )108 109 # 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"112 112- 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_name115 115- 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}"120 120- # 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+ )141 125- 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- continue148-149- 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- continue155-156- code = CodeType(*code_args)157- except Exception:158- # Some environments such as Google App Engine don't support159- # modifying code objects.160- pass161-142 # 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 linesmodified:src/jinja2/environment.py+11 added-24 removed
1112 unmodified lines1113 return ChainMap(d, self.globals)1114 1115 1116 class 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.1118 1120- 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.1122 1125- 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.1128 1129- 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.1133-1134- >>> 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 """1132 1133 #: Type of environment to create when creating a template directly1134 #: rather than through an existing environment.517 unmodified linesmodified:src/jinja2/loaders.py+12 added-4 removed
295 unmodified lines296 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] = []302+303+ # 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))310+311+ for root in roots:312 root = os.path.join(root, package_path)313 314 if os.path.isdir(root):315 template_root = root337 unmodified linesmodified:src/jinja2/nativetypes.py+7 added-1 removed
1 import typing as t2 from ast import literal_eval3+from ast import parse4 from itertools import chain5 from itertools import islice6 7 from . import nodes25 unmodified lines33 else:34 raw = "".join([str(v) for v in chain(head, values)])35 36 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 raw45 46 78 unmodified linesmodified:src/jinja2/nodes.py+2 added-3 removed
239 unmodified lines240 return NotImplemented241 242 return tuple(self.iter_fields()) == tuple(other.iter_fields())243 244- def __hash__(self) -> int:245- return hash(tuple(self.iter_fields()))244+ __hash__ = object.__hash__245 246 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 lines954 operator = "/"955 956 957 class 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 """961 962 operator = "//"242 unmodified linesmodified:tests/test_inheritance.py+2 added-2 removed
35 unmodified lines36 {% 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 lines48 {% 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 linesmodified:tests/test_loader.py+22 added
312 unmodified lines313 assert "test.html" in templates314 315 316 @pytest.fixture()317+def package_file_loader(monkeypatch):318+ monkeypatch.syspath_prepend(Path(__file__).parent / "res")319+ return PackageLoader("__init__")320+321+322+@pytest.mark.parametrize(323+ ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]324+)325+def 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()330+331+332+def 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 templates336+337+338+@pytest.fixture()339 def 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 linesmodified:tests/test_nativetypes.py+6 added
145 unmodified lines146 147 def test_spontaneous_env():148 t = NativeTemplate("{{ true }}")149 assert isinstance(t.environment, NativeEnvironment)150+151+152+def 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
1+def test_template_hash(env):2+ template = env.parse("hash test")3+ hash(template)modified:CHANGES.rst+18 added-1 removed
4 unmodified lines5 6 Unreleased7 8 9+Version 3.0.310+-------------11+12+Released 2021-11-0913+14+- 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`24+25+26 Version 3.0.227 -------------28 29 Released 2021-10-04400 unmodified lines430 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