environment.py
This file
Path
src/jinja2/environment.py
1,666 lines · 59.4 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1–3why, one step back1"""Classes for managing templates and their runtime and compile time2options.3"""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 4why, one step back4update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 5why, one step back5import osMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 6why, one step back6import typingMerge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 7why, one step back7import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 8why, one step back8import weakrefMerge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
line 9why, one step back9from collections import ChainMapdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 10why, one step back10from contextlib import aclosingMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 11why, one step back11from functools import lru_cacheupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 12–13why, one step back12from functools import partial13from functools import reduceMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 14why, one step back14from types import CodeTypeupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 15–24why, one step back1516from markupsafe import Markup1718from . import nodes19from .compiler import CodeGenerator20from .compiler import generate21from .defaults import BLOCK_END_STRING22from .defaults import BLOCK_START_STRING23from .defaults import COMMENT_END_STRING24from .defaults import COMMENT_START_STRINGMerge branch '3.1.x'David Lordbefore adoptionde61312
line 25why, one step back25from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 26–27why, one step back26from .defaults import DEFAULT_NAMESPACE27from .defaults import DEFAULT_POLICIESMerge branch '3.1.x'David Lordbefore adoptionde61312
line 28why, one step back28from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 29–42why, one step back29from .defaults import KEEP_TRAILING_NEWLINE30from .defaults import LINE_COMMENT_PREFIX31from .defaults import LINE_STATEMENT_PREFIX32from .defaults import LSTRIP_BLOCKS33from .defaults import NEWLINE_SEQUENCE34from .defaults import TRIM_BLOCKS35from .defaults import VARIABLE_END_STRING36from .defaults import VARIABLE_START_STRING37from .exceptions import TemplateNotFound38from .exceptions import TemplateRuntimeError39from .exceptions import TemplatesNotFound40from .exceptions import TemplateSyntaxError41from .exceptions import UndefinedError42from .lexer import get_lexerMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 43why, one step back43from .lexer import Lexerupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 44–49why, one step back44from .lexer import TokenStream45from .nodes import EvalContext46from .parser import Parser47from .runtime import Context48from .runtime import new_context49from .runtime import UndefinedMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 50why, one step back50from .utils import _PassArgupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 51–57why, one step back51from .utils import concat52from .utils import consume53from .utils import import_string54from .utils import internalcode55from .utils import LRUCache56from .utils import missing57Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 58–59why, one step back58if t.TYPE_CHECKING:59 import typing_extensions as teMerge branch '3.1.x'David Lordbefore adoptionde61312
line 60why, one step back60Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 61–63why, one step back61 from .bccache import BytecodeCache62 from .ext import Extension63 from .loaders import BaseLoaderupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 64why, one step back64Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 65why, one step back65_env_bound = t.TypeVar("_env_bound", bound="Environment")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 66why, one step back66Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 67–69why, one step back6768# for direct template usage we have up to ten living environments69@lru_cache(maxsize=10)Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 70why, one step back70def get_spontaneous_environment(cls: type[_env_bound], *args: t.Any) -> _env_bound:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 71–77why, one step back71 """Return a new spontaneous environment. A spontaneous environment72 is used for templates created directly rather than through an73 existing environment.7475 :param cls: Environment class to create.76 :param args: Positional arguments passed to environment.77 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 78–80why, one step back78 env = cls(*args)79 env.shared = True80 return envupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 81–82why, one step back8182Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 83–84why, one step back83def create_cache(84 size: int,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 85why, one step back85) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 86–88why, one step back86 """Return the cache class for the given size."""87 if size == 0:88 return NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 89why, one step back89update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 90–92why, one step back90 if size < 0:91 return {}92Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 93why, one step back93 return LRUCache(size) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 94why, one step back94Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 95–96why, one step back9596def copy_cache(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 97–98why, one step back97 cache: t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None,98) -> t.MutableMapping[tuple["weakref.ref[BaseLoader]", str], "Template"] | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 99–101why, one step back99 """Create an empty copy of the given cache."""100 if cache is None:101 return NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 102why, one step back102Merge branch '3.1.x'David Lordbefore adoptionde61312
line 103why, one step back103 if type(cache) is dict: # noqa E721update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 104–105why, one step back104 return {}105Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 106why, one step back106 return LRUCache(cache.capacity) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 107why, one step back107Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 108–110why, one step back108109def load_extensions(110 environment: "Environment",drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 111why, one step back111 extensions: t.Sequence[str | type["Extension"]],Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 112why, one step back112) -> dict[str, "Extension"]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 113why, one step back113 """Load the extensions from the list and bind it to the environment.Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 114why, one step back114 Returns a dict of instantiated extensions.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 115–116why, one step back115 """116 result = {}Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 117why, one step back117update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 118–119why, one step back118 for extension in extensions:119 if isinstance(extension, str):Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 120why, one step back120 extension = t.cast(type["Extension"], import_string(extension))Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 121why, one step back121update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 122why, one step back122 result[extension.identifier] = extension(environment)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 123why, one step back123update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 124–126why, one step back124 return result125126Merge branch 'stable'David Lordbefore adoption6aeab5d
line 127why, one step back127def _environment_config_check(environment: _env_bound) -> _env_bound:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 128why, one step back128 """Perform a sanity check on the environment."""Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 129–131why, one step back129 assert issubclass(environment.undefined, Undefined), (130 "'undefined' must be a subclass of 'jinja2.Undefined'."131 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 132–135why, one step back132 assert (133 environment.block_start_string134 != environment.variable_start_string135 != environment.comment_start_stringMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 136why, one step back136 ), "block, variable and comment start strings must be different."update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 137–140why, one step back137 assert environment.newline_sequence in {138 "\r",139 "\r\n",140 "\n",Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 141why, one step back141 }, "'newline_sequence' must be one of '\\n', '\\r\\n', or '\\r'."update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 142–276why, one step back142 return environment143144145class Environment:146 r"""The core component of Jinja is the `Environment`. It contains147 important shared variables like configuration, filters, tests,148 globals and others. Instances of this class may be modified if149 they are not shared and if no template was loaded so far.150 Modifications on environments after the first template was loaded151 will lead to surprising effects and undefined behavior.152153 Here are the possible initialization parameters:154155 `block_start_string`156 The string marking the beginning of a block. Defaults to ``'{%'``.157158 `block_end_string`159 The string marking the end of a block. Defaults to ``'%}'``.160161 `variable_start_string`162 The string marking the beginning of a print statement.163 Defaults to ``'{{'``.164165 `variable_end_string`166 The string marking the end of a print statement. Defaults to167 ``'}}'``.168169 `comment_start_string`170 The string marking the beginning of a comment. Defaults to ``'{#'``.171172 `comment_end_string`173 The string marking the end of a comment. Defaults to ``'#}'``.174175 `line_statement_prefix`176 If given and a string, this will be used as prefix for line based177 statements. See also :ref:`line-statements`.178179 `line_comment_prefix`180 If given and a string, this will be used as prefix for line based181 comments. See also :ref:`line-statements`.182183 .. versionadded:: 2.2184185 `trim_blocks`186 If this is set to ``True`` the first newline after a block is187 removed (block, not variable tag!). Defaults to `False`.188189 `lstrip_blocks`190 If this is set to ``True`` leading spaces and tabs are stripped191 from the start of a line to a block. Defaults to `False`.192193 `newline_sequence`194 The sequence that starts a newline. Must be one of ``'\r'``,195 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a196 useful default for Linux and OS X systems as well as web197 applications.198199 `keep_trailing_newline`200 Preserve the trailing newline when rendering templates.201 The default is ``False``, which causes a single newline,202 if present, to be stripped from the end of the template.203204 .. versionadded:: 2.7205206 `extensions`207 List of Jinja extensions to use. This can either be import paths208 as strings or extension classes. For more information have a209 look at :ref:`the extensions documentation <jinja-extensions>`.210211 `optimized`212 should the optimizer be enabled? Default is ``True``.213214 `undefined`215 :class:`Undefined` or a subclass of it that is used to represent216 undefined values in the template.217218 `finalize`219 A callable that can be used to process the result of a variable220 expression before it is output. For example one can convert221 ``None`` implicitly into an empty string here.222223 `autoescape`224 If set to ``True`` the XML/HTML autoescaping feature is enabled by225 default. For more details about autoescaping see226 :class:`~markupsafe.Markup`. As of Jinja 2.4 this can also227 be a callable that is passed the template name and has to228 return ``True`` or ``False`` depending on autoescape should be229 enabled by default.230231 .. versionchanged:: 2.4232 `autoescape` can now be a function233234 `loader`235 The template loader for this environment.236237 `cache_size`238 The size of the cache. Per default this is ``400`` which means239 that if more than 400 templates are loaded the loader will clean240 out the least recently used template. If the cache size is set to241 ``0`` templates are recompiled all the time, if the cache size is242 ``-1`` the cache will not be cleaned.243244 .. versionchanged:: 2.8245 The cache size was increased to 400 from a low 50.246247 `auto_reload`248 Some loaders load templates from locations where the template249 sources may change (ie: file system or database). If250 ``auto_reload`` is set to ``True`` (default) every time a template is251 requested the loader checks if the source changed and if yes, it252 will reload the template. For higher performance it's possible to253 disable that.254255 `bytecode_cache`256 If set to a bytecode cache object, this object will provide a257 cache for the internal Jinja bytecode so that templates don't258 have to be parsed if they were not changed.259260 See :ref:`bytecode-cache` for more information.261262 `enable_async`263 If set to true this enables async template execution which264 allows using async functions and generators.265 """266267 #: if this environment is sandboxed. Modifying this variable won't make268 #: the environment sandboxed though. For a real sandboxed environment269 #: have a look at jinja2.sandbox. This flag alone controls the code270 #: generation by the compiler.271 sandboxed = False272273 #: True if the environment is just an overlay274 overlayed = False275276 #: the environment this environment is linked to if it is an overlayMerge pull request #1361 from pallets/consistencyDavid Lordbefore adoptionab9cd8c
line 277why, one step back277 linked_to: t.Optional["Environment"] = Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 278–284why, one step back278279 #: shared environments have this set to `True`. A shared environment280 #: must not be modified281 shared = False282283 #: the class that is used for code generation. See284 #: :class:`~jinja2.compiler.CodeGenerator` for more information.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 285why, one step back285 code_generator_class: type["CodeGenerator"] = CodeGeneratorupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 286why, one step back286Merge pull request #1511 from mkrizek/issue-1510David Lordbefore adoption7d72eb7
lines 287–288why, one step back287 concat = "".join288update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 289–290why, one step back289 #: the context class that is used for templates. See290 #: :class:`~jinja2.runtime.Context` for more information.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 291why, one step back291 context_class: type[Context] = Contextupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 292why, one step back292Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 293why, one step back293 template_class: type["Template"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 294–296why, one step back294295 def __init__(296 self,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 297–302why, one step back297 block_start_string: str = BLOCK_START_STRING,298 block_end_string: str = BLOCK_END_STRING,299 variable_start_string: str = VARIABLE_START_STRING,300 variable_end_string: str = VARIABLE_END_STRING,301 comment_start_string: str = COMMENT_START_STRING,302 comment_end_string: str = COMMENT_END_STRING,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 303–304why, one step back303 line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,304 line_comment_prefix: str | None = LINE_COMMENT_PREFIX,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 305–308why, one step back305 trim_blocks: bool = TRIM_BLOCKS,306 lstrip_blocks: bool = LSTRIP_BLOCKS,307 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,308 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 309why, one step back309 extensions: t.Sequence[str | type["Extension"]] = (),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 310why, one step back310 optimized: bool = True,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 311why, one step back311 undefined: type[Undefined] = Undefined,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 312–313why, one step back312 finalize: t.Callable[..., t.Any] | None = None,313 autoescape: bool | t.Callable[[str | None], bool] = False,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 314–318why, one step back314 loader: t.Optional["BaseLoader"] = None,315 cache_size: int = 400,316 auto_reload: bool = True,317 bytecode_cache: t.Optional["BytecodeCache"] = None,318 enable_async: bool = False,update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 319–345why, one step back319 ):320 # !!Important notice!!321 # The constructor accepts quite a few arguments that should be322 # passed by keyword rather than position. However it's important to323 # not change the order of arguments because it's used at least324 # internally in those cases:325 # - spontaneous environments (i18n extension and Template)326 # - unittests327 # If parameter changes are required only add parameters at the end328 # and don't change the arguments (or the defaults!) of the arguments329 # existing already.330331 # lexer / parser information332 self.block_start_string = block_start_string333 self.block_end_string = block_end_string334 self.variable_start_string = variable_start_string335 self.variable_end_string = variable_end_string336 self.comment_start_string = comment_start_string337 self.comment_end_string = comment_end_string338 self.line_statement_prefix = line_statement_prefix339 self.line_comment_prefix = line_comment_prefix340 self.trim_blocks = trim_blocks341 self.lstrip_blocks = lstrip_blocks342 self.newline_sequence = newline_sequence343 self.keep_trailing_newline = keep_trailing_newline344345 # runtime informationUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 346why, one step back346 self.undefined: type[Undefined] = undefinedupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 347–367why, one step back347 self.optimized = optimized348 self.finalize = finalize349 self.autoescape = autoescape350351 # defaults352 self.filters = DEFAULT_FILTERS.copy()353 self.tests = DEFAULT_TESTS.copy()354 self.globals = DEFAULT_NAMESPACE.copy()355356 # set the loader provided357 self.loader = loader358 self.cache = create_cache(cache_size)359 self.bytecode_cache = bytecode_cache360 self.auto_reload = auto_reload361362 # configurable policies363 self.policies = DEFAULT_POLICIES.copy()364365 # load extensions366 self.extensions = load_extensions(self, extensions)367Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 368why, one step back368 self.is_async = enable_asyncMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 369why, one step back369 _environment_config_check(self)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 370why, one step back370drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 371why, one step back371 def add_extension(self, extension: str | type["Extension"]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 372–377why, one step back372 """Adds an extension after the environment was created.373374 .. versionadded:: 2.5375 """376 self.extensions.update(load_extensions(self, [extension]))377Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 378why, one step back378 def extend(self, **attributes: t.Any) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 379–388why, one step back379 """Add the items to the instance of the environment if they do not exist380 yet. This is used by :ref:`extensions <writing-extensions>` to register381 callbacks and configuration values without breaking inheritance.382 """383 for key, value in attributes.items():384 if not hasattr(self, key):385 setattr(self, key, value)386387 def overlay(388 self,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 389–394why, one step back389 block_start_string: str = missing,390 block_end_string: str = missing,391 variable_start_string: str = missing,392 variable_end_string: str = missing,393 comment_start_string: str = missing,394 comment_end_string: str = missing,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 395–396why, one step back395 line_statement_prefix: str | None = missing,396 line_comment_prefix: str | None = missing,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 397–398why, one step back397 trim_blocks: bool = missing,398 lstrip_blocks: bool = missing,Merge branch '3.1.x'David Lordbefore adoptiona0dd775
lines 399–400why, one step back399 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = missing,400 keep_trailing_newline: bool = missing,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 401why, one step back401 extensions: t.Sequence[str | type["Extension"]] = missing,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 402why, one step back402 optimized: bool = missing,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 403why, one step back403 undefined: type[Undefined] = missing,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 404–405why, one step back404 finalize: t.Callable[..., t.Any] | None = missing,405 autoescape: bool | t.Callable[[str | None], bool] = missing,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 406–409why, one step back406 loader: t.Optional["BaseLoader"] = missing,407 cache_size: int = missing,408 auto_reload: bool = missing,409 bytecode_cache: t.Optional["BytecodeCache"] = missing,Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 410–411why, one step back410 enable_async: bool = missing,411 ) -> "te.Self":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 412–421why, one step back412 """Create a new overlay environment that shares all the data with the413 current environment except for cache and the overridden attributes.414 Extensions cannot be removed for an overlayed environment. An overlayed415 environment automatically gets all the extensions of the environment it416 is linked to plus optional extra extensions.417418 Creating overlays should happen after the initial environment was set419 up completely. Not all attributes are truly linked, some are just420 copied over so modifications on the original environment may not shine421 through.Merge branch '3.1.x'David Lordbefore adoptiona0dd775
line 422why, one step back422Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 423–425why, one step back423 .. versionchanged:: 3.1.5424 ``enable_async`` is applied correctly.425Merge branch '3.1.x'David Lordbefore adoptiona0dd775
line 426why, one step back426 .. versionchanged:: 3.1.2Merge branch 'stable'David Lordbefore adoption6aeab5d
line 427why, one step back427 Added the ``newline_sequence``, ``keep_trailing_newline``,Merge branch '3.1.x'David Lordbefore adoptiona0dd775
line 428why, one step back428 and ``enable_async`` parameters to match ``__init__``.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 429–430why, one step back429 """430 args = dict(locals())Merge branch '3.1.x'David Lordbefore adoptiona0dd775
line 431why, one step back431 del args["self"], args["cache_size"], args["extensions"], args["enable_async"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 432–451why, one step back432433 rv = object.__new__(self.__class__)434 rv.__dict__.update(self.__dict__)435 rv.overlayed = True436 rv.linked_to = self437438 for key, value in args.items():439 if value is not missing:440 setattr(rv, key, value)441442 if cache_size is not missing:443 rv.cache = create_cache(cache_size)444 else:445 rv.cache = copy_cache(self.cache)446447 rv.extensions = {}448 for key, value in self.extensions.items():449 rv.extensions[key] = value.bind(rv)450 if extensions is not missing:451 rv.extensions.update(load_extensions(rv, extensions))Merge branch '3.1.x'David Lordbefore adoptiona0dd775
lines 452–454why, one step back452453 if enable_async is not missing:454 rv.is_async = enable_asyncupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 455why, one step back455Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 456why, one step back456 return _environment_config_check(rv)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 457why, one step back457Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 458–461why, one step back458 @property459 def lexer(self) -> Lexer:460 """The lexer for this environment."""461 return get_lexer(self)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 462why, one step back462Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 463why, one step back463 def iter_extensions(self) -> t.Iterator["Extension"]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 464–466why, one step back464 """Iterates over the extensions by priority."""465 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))466drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 467why, one step back467 def getitem(self, obj: t.Any, argument: str | t.Any) -> t.Any | Undefined:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 468–483why, one step back468 """Get an item or attribute of an object but prefer the item."""469 try:470 return obj[argument]471 except (AttributeError, TypeError, LookupError):472 if isinstance(argument, str):473 try:474 attr = str(argument)475 except Exception:476 pass477 else:478 try:479 return getattr(obj, attr)480 except AttributeError:481 pass482 return self.undefined(obj=obj, name=argument)483Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 484why, one step back484 def getattr(self, obj: t.Any, attribute: str) -> t.Any:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 485why, one step back485 """Get an item or attribute of an object but prefer the attribute.Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 486why, one step back486 Unlike :meth:`getitem` the attribute *must* be a string.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 487–496why, one step back487 """488 try:489 return getattr(obj, attribute)490 except AttributeError:491 pass492 try:493 return obj[attribute]494 except (TypeError, LookupError, AttributeError):495 return self.undefined(obj=obj, name=attribute)496Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 497why, one step back497 def _filter_test_common(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 498why, one step back498 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 499why, one step back499 name: str | Undefined,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 500why, one step back500 value: t.Any,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 501–504why, one step back501 args: t.Sequence[t.Any] | None,502 kwargs: t.Mapping[str, t.Any] | None,503 context: Context | None,504 eval_ctx: EvalContext | None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 505–506why, one step back505 is_filter: bool,506 ) -> t.Any:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 507–508why, one step back507 if is_filter:508 env_map = self.filtersMerge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 509why, one step back509 type_name = "filter"Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 510–512why, one step back510 else:511 env_map = self.tests512 type_name = "test"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 513why, one step back513Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 514why, one step back514 func = env_map.get(name) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 515–516why, one step back515516 if func is None:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 517–528why, one step back517 msg = f"No {type_name} named {name!r}."518519 if isinstance(name, Undefined):520 try:521 name._fail_with_undefined_error()522 except Exception as e:523 msg = f"{msg} ({e}; did you forget to quote the callable name?)"524525 raise TemplateRuntimeError(msg)526527 args = [value, *(args if args is not None else ())]528 kwargs = kwargs if kwargs is not None else {}Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 529why, one step back529 pass_arg = _PassArg.from_obj(func)Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 530why, one step back530Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 531why, one step back531 if pass_arg is _PassArg.context:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 532–533why, one step back532 if context is None:533 raise TemplateRuntimeError(Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 534why, one step back534 f"Attempted to invoke a context {type_name} without context."update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 535why, one step back535 )Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 536why, one step back536update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 537why, one step back537 args.insert(0, context)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 538why, one step back538 elif pass_arg is _PassArg.eval_context:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 539–543why, one step back539 if eval_ctx is None:540 if context is not None:541 eval_ctx = context.eval_ctx542 else:543 eval_ctx = EvalContext(self)Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 544why, one step back544update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 545why, one step back545 args.insert(0, eval_ctx)Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 546why, one step back546 elif pass_arg is _PassArg.environment:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 547–548why, one step back547 args.insert(0, self)548Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 549why, one step back549 return func(*args, **kwargs)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 550why, one step back550Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
line 551why, one step back551 def call_filter(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 552–554why, one step back552 self,553 name: str,554 value: t.Any,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 555–558why, one step back555 args: t.Sequence[t.Any] | None = None,556 kwargs: t.Mapping[str, t.Any] | None = None,557 context: Context | None = None,558 eval_ctx: EvalContext | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 559why, one step back559 ) -> t.Any:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 560–565why, one step back560 """Invoke a filter on a value the same way the compiler does.561562 This might return a coroutine if the filter is running from an563 environment in async mode and the filter supports async564 execution. It's your responsibility to await this if needed.565update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 566–567why, one step back566 .. versionadded:: 2.7567 """Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 568–572why, one step back568 return self._filter_test_common(569 name, value, args, kwargs, context, eval_ctx, True570 )571572 def call_test(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 573–575why, one step back573 self,574 name: str,575 value: t.Any,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 576–579why, one step back576 args: t.Sequence[t.Any] | None = None,577 kwargs: t.Mapping[str, t.Any] | None = None,578 context: Context | None = None,579 eval_ctx: EvalContext | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 580why, one step back580 ) -> t.Any:Merge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 581–587why, one step back581 """Invoke a test on a value the same way the compiler does.582583 This might return a coroutine if the test is running from an584 environment in async mode and the test supports async execution.585 It's your responsibility to await this if needed.586587 .. versionchanged:: 3.0Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8
line 588why, one step back588 Tests support ``@pass_context``, etc. decorators. AddedMerge pull request #1383 from pallets/test-decoratorsDavid Lordbefore adoptionbeabf30
lines 589–595why, one step back589 the ``context`` and ``eval_ctx`` parameters.590591 .. versionadded:: 2.7592 """593 return self._filter_test_common(594 name, value, args, kwargs, context, eval_ctx, False595 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 596–597why, one step back596597 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 598–600why, one step back598 def parse(599 self,600 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 601–602why, one step back601 name: str | None = None,602 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 603why, one step back603 ) -> nodes.Template:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 604–616why, one step back604 """Parse the sourcecode and return the abstract syntax tree. This605 tree of nodes is used by the compiler to convert the template into606 executable source- or bytecode. This is useful for debugging or to607 extract information from templates.608609 If you are :ref:`developing Jinja extensions <writing-extensions>`610 this gives you a good overview of the node tree generated.611 """612 try:613 return self._parse(source, name, filename)614 except TemplateSyntaxError:615 self.handle_exception(source=source)616Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 617why, one step back617 def _parse(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 618why, one step back618 self, source: str, name: str | None, filename: str | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 619why, one step back619 ) -> nodes.Template:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 620–622why, one step back620 """Internal parsing function used by `parse` and `compile`."""621 return Parser(self, source, name, filename).parse()622Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 623–625why, one step back623 def lex(624 self,625 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 626–627why, one step back626 name: str | None = None,627 filename: str | None = None,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 628why, one step back628 ) -> t.Iterator[tuple[int, str, str]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 629–643why, one step back629 """Lex the given sourcecode and return a generator that yields630 tokens as tuples in the form ``(lineno, token_type, value)``.631 This can be useful for :ref:`extension development <writing-extensions>`632 and debugging templates.633634 This does not perform preprocessing. If you want the preprocessing635 of the extensions to be applied you have to filter source through636 the :meth:`preprocess` method.637 """638 source = str(source)639 try:640 return self.lexer.tokeniter(source, name, filename)641 except TemplateSyntaxError:642 self.handle_exception(source=source)643Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 644–646why, one step back644 def preprocess(645 self,646 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 647–648why, one step back647 name: str | None = None,648 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 649why, one step back649 ) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 650–659why, one step back650 """Preprocesses the source with all extensions. This is automatically651 called for all parsing and compiling methods but *not* for :meth:`lex`652 because there you usually only want the actual source tokenized.653 """654 return reduce(655 lambda s, e: e.preprocess(s, name, filename),656 self.iter_extensions(),657 str(source),658 )659Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 660–662why, one step back660 def _tokenize(661 self,662 source: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 663–665why, one step back663 name: str | None,664 filename: str | None = None,665 state: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 666why, one step back666 ) -> TokenStream:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 667–671why, one step back667 """Called by the parser to do the preprocessing and filtering668 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.669 """670 source = self.preprocess(source, name, filename)671 stream = self.lexer.tokenize(source, name, filename, state)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 672why, one step back672update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 673why, one step back673 for ext in self.iter_extensions():Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 674–675why, one step back674 stream = ext.filter_stream(stream) # type: ignore675update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 676why, one step back676 if not isinstance(stream, TokenStream):Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 677why, one step back677 stream = TokenStream(stream, name, filename)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 678why, one step back678update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 679–680why, one step back679 return stream680Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 681–683why, one step back681 def _generate(682 self,683 source: nodes.Template,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 684–685why, one step back684 name: str | None,685 filename: str | None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 686–687why, one step back686 defer_init: bool = False,687 ) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 688–692why, one step back688 """Internal hook that can be overridden to hook a different generate689 method in.690691 .. versionadded:: 2.5692 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 693why, one step back693 return generate( # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 694–701why, one step back694 source,695 self,696 name,697 filename,698 defer_init=defer_init,699 optimized=self.optimized,700 )701Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 702why, one step back702 def _compile(self, source: str, filename: str) -> CodeType:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 703–707why, one step back703 """Internal hook that can be overridden to hook a different compile704 method in.705706 .. versionadded:: 2.5707 """Merge branch '3.1.x'David Lordbefore adoption81a2384
line 708why, one step back708 return compile(source, filename, "exec")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 709why, one step back709Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 710why, one step back710 @typing.overloadMerge branch '3.1.x'David Lordbefore adoption7f0fc0a
line 711why, one step back711 def compile(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 712why, one step back712 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 713–715why, one step back713 source: str | nodes.Template,714 name: str | None = None,715 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 716–717why, one step back716 raw: "te.Literal[False]" = False,717 defer_init: bool = False,Merge branch '3.1.x'David Lordbefore adoptionde61312
line 718why, one step back718 ) -> CodeType: ...Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 719–722why, one step back719720 @typing.overload721 def compile(722 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 723–725why, one step back723 source: str | nodes.Template,724 name: str | None = None,725 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 726–727why, one step back726 raw: "te.Literal[True]" = ...,727 defer_init: bool = False,Merge branch '3.1.x'David Lordbefore adoptionde61312
line 728why, one step back728 ) -> str: ...Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 729why, one step back729update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 730why, one step back730 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 731–732why, one step back731 def compile(732 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 733–735why, one step back733 source: str | nodes.Template,734 name: str | None = None,735 filename: str | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 736–737why, one step back736 raw: bool = False,737 defer_init: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 738why, one step back738 ) -> str | CodeType:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 739–771why, one step back739 """Compile a node or template source code. The `name` parameter is740 the load name of the template after it was joined using741 :meth:`join_path` if necessary, not the filename on the file system.742 the `filename` parameter is the estimated filename of the template on743 the file system. If the template came from a database or memory this744 can be omitted.745746 The return value of this method is a python code object. If the `raw`747 parameter is `True` the return value will be a string with python748 code equivalent to the bytecode returned otherwise. This method is749 mainly used internally.750751 `defer_init` is use internally to aid the module code generator. This752 causes the generated code to be able to import without the global753 environment variable to be set.754755 .. versionadded:: 2.4756 `defer_init` parameter added.757 """758 source_hint = None759 try:760 if isinstance(source, str):761 source_hint = source762 source = self._parse(source, name, filename)763 source = self._generate(source, name, filename, defer_init=defer_init)764 if raw:765 return source766 if filename is None:767 filename = "<template>"768 return self._compile(source, filename)769 except TemplateSyntaxError:770 self.handle_exception(source=source_hint)771Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 772–774why, one step back772 def compile_expression(773 self, source: str, undefined_to_none: bool = True774 ) -> "TemplateExpression":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 775–810why, one step back775 """A handy helper method that returns a callable that accepts keyword776 arguments that appear as variables in the expression. If called it777 returns the result of the expression.778779 This is useful if applications want to use the same rules as Jinja780 in template "configuration files" or similar situations.781782 Example usage:783784 >>> env = Environment()785 >>> expr = env.compile_expression('foo == 42')786 >>> expr(foo=23)787 False788 >>> expr(foo=42)789 True790791 Per default the return value is converted to `None` if the792 expression returns an undefined value. This can be changed793 by setting `undefined_to_none` to `False`.794795 >>> env.compile_expression('var')() is None796 True797 >>> env.compile_expression('var', undefined_to_none=False)()798 Undefined799800 .. versionadded:: 2.1801 """802 parser = Parser(self, source, state="variable")803 try:804 expr = parser.parse_expression()805 if not parser.stream.eos:806 raise TemplateSyntaxError(807 "chunk after expression", parser.stream.current.lineno, None, None808 )809 expr.set_environment(self)810 except TemplateSyntaxError:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 811why, one step back811 self.handle_exception(source=source)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 812–818why, one step back812813 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]814 template = self.from_string(nodes.Template(body, lineno=1))815 return TemplateExpression(template, undefined_to_none)816817 def compile_templates(818 self,switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
line 819why, one step back819 target: t.Union[str, "os.PathLike[str]"],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 820–823why, one step back820 extensions: t.Collection[str] | None = None,821 filter_func: t.Callable[[str], bool] | None = None,822 zip: str | None = "deflated",823 log_function: t.Callable[[str], None] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 824–825why, one step back824 ignore_errors: bool = True,825 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 826–846why, one step back826 """Finds all the templates the loader can find, compiles them827 and stores them in `target`. If `zip` is `None`, instead of in a828 zipfile, the templates will be stored in a directory.829 By default a deflate zip algorithm is used. To switch to830 the stored algorithm, `zip` can be set to ``'stored'``.831832 `extensions` and `filter_func` are passed to :meth:`list_templates`.833 Each template returned will be compiled to the target folder or834 zipfile.835836 By default template compilation errors are ignored. In case a837 log function is provided, errors are logged. If you want template838 syntax errors to abort the compilation you can set `ignore_errors`839 to `False` and you will get an exception on syntax errors.840841 .. versionadded:: 2.4842 """843 from .loaders import ModuleLoader844845 if log_function is None:846Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 847why, one step back847 def log_function(x: str) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 848–849why, one step back848 pass849Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 850–853why, one step back850 assert log_function is not None851 assert self.loader is not None, "No loader configured."852853 def write_file(filename: str, data: str) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 854–859why, one step back854 if zip:855 info = ZipInfo(filename)856 info.external_attr = 0o755 << 16857 zip_file.writestr(info, data)858 else:859 with open(os.path.join(target, filename), "wb") as f:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 860why, one step back860 f.write(data.encode("utf8"))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 861–862why, one step back861862 if zip is not None:Merge branch '3.1.x'David Lordbefore adoptionde61312
lines 863–866why, one step back863 from zipfile import ZIP_DEFLATED864 from zipfile import ZIP_STORED865 from zipfile import ZipFile866 from zipfile import ZipInfoupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 867–897why, one step back867868 zip_file = ZipFile(869 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]870 )871 log_function(f"Compiling into Zip archive {target!r}")872 else:873 if not os.path.isdir(target):874 os.makedirs(target)875 log_function(f"Compiling into folder {target!r}")876877 try:878 for name in self.list_templates(extensions, filter_func):879 source, filename, _ = self.loader.get_source(self, name)880 try:881 code = self.compile(source, name, filename, True, True)882 except TemplateSyntaxError as e:883 if not ignore_errors:884 raise885 log_function(f'Could not compile "{name}": {e}')886 continue887888 filename = ModuleLoader.get_module_filename(name)889890 write_file(filename, code)891 log_function(f'Compiled "{name}" as {filename}')892 finally:893 if zip:894 zip_file.close()895896 log_function("Finished compiling templates")897Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 898–899why, one step back898 def list_templates(899 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 900–901why, one step back900 extensions: t.Collection[str] | None = None,901 filter_func: t.Callable[[str], bool] | None = None,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 902why, one step back902 ) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 903–917why, one step back903 """Returns a list of templates for this environment. This requires904 that the loader supports the loader's905 :meth:`~BaseLoader.list_templates` method.906907 If there are other files in the template folder besides the908 actual templates, the returned list can be filtered. There are two909 ways: either `extensions` is set to a list of file extensions for910 templates, or a `filter_func` can be provided which is a callable that911 is passed a template name and should return `True` if it should end up912 in the result list.913914 If the loader does not support that, a :exc:`TypeError` is raised.915916 .. versionadded:: 2.4917 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 918why, one step back918 assert self.loader is not None, "No loader configured."update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 919–926why, one step back919 names = self.loader.list_templates()920921 if extensions is not None:922 if filter_func is not None:923 raise TypeError(924 "either extensions or filter_func can be passed, but not both"925 )926Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 927why, one step back927 def filter_func(x: str) -> bool:Merge branch '3.1.x'David Lordbefore adoptionc0e4f69
line 928why, one step back928 return "." in x and x.rsplit(".", 1)[1] in extensionsupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 929–934why, one step back929930 if filter_func is not None:931 names = [name for name in names if filter_func(name)]932933 return names934drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 935why, one step back935 def handle_exception(self, source: str | None = None) -> "te.NoReturn":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 936–942why, one step back936 """Exception handling helper. This is used internally to either raise937 rewritten exceptions or return a rendered traceback for the template.938 """939 from .debug import rewrite_traceback_stack940941 raise rewrite_traceback_stack(source=source)942Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 943why, one step back943 def join_path(self, template: str, parent: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 944–955why, one step back944 """Join a template with the parent. By default all the lookups are945 relative to the loader root so this method returns the `template`946 parameter unchanged, but if the paths should be relative to the947 parent template, this function can be used to calculate the real948 template name.949950 Subclasses may override this method and implement template path951 joining here.952 """953 return template954955 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 956why, one step back956 def _load_template(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 957why, one step back957 self, name: str, globals: t.MutableMapping[str, t.Any] | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 958why, one step back958 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 959–966why, one step back959 if self.loader is None:960 raise TypeError("no loader for this environment specified")961 cache_key = (weakref.ref(self.loader), name)962 if self.cache is not None:963 template = self.cache.get(cache_key)964 if template is not None and (965 not self.auto_reload or template.is_up_to_date966 ):Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 967–971why, one step back967 # template.globals is a ChainMap, modifying it will only968 # affect the template, not the environment globals.969 if globals:970 template.globals.update(globals)971update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 972why, one step back972 return templateMerge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 973–975why, one step back973974 template = self.loader.load(self, name, self.make_globals(globals))975update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 976–980why, one step back976 if self.cache is not None:977 self.cache[cache_key] = template978 return template979980 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 981–983why, one step back981 def get_template(982 self,983 name: t.Union[str, "Template"],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 984–985why, one step back984 parent: str | None = None,985 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 986why, one step back986 ) -> "Template":Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 987–989why, one step back987 """Load a template by name with :attr:`loader` and return a988 :class:`Template`. If the template does not exist a989 :exc:`TemplateNotFound` exception is raised.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 990why, one step back990Merge branch '3.0.x'David Lordbefore adoptionbb7f3a5
lines 991–993why, one step back991 :param name: Name of the template to load. When loading992 templates from the filesystem, "/" is used as the path993 separator, even on Windows.Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 994–1000why, one step back994 :param parent: The name of the parent template importing this995 template. :meth:`join_path` can be used to implement name996 transformations with this.997 :param globals: Extend the environment :attr:`globals` with998 these extra variables available for all renders of this999 template. If the template has already been loaded and1000 cached, its globals are updated with any new items.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1001why, one step back1001Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1002–1004why, one step back1002 .. versionchanged:: 3.01003 If a template is loaded from cache, ``globals`` will update1004 the template's globals instead of ignoring the new values.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1005–1006why, one step back10051006 .. versionchanged:: 2.4Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1007–1008why, one step back1007 If ``name`` is a :class:`Template` object it is returned1008 unchanged.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1009–1014why, one step back1009 """1010 if isinstance(name, Template):1011 return name1012 if parent is not None:1013 name = self.join_path(name, parent)1014Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1015–1016why, one step back1015 return self._load_template(name, globals)1016update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1017why, one step back1017 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1018–1020why, one step back1018 def select_template(1019 self,1020 names: t.Iterable[t.Union[str, "Template"]],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1021–1022why, one step back1021 parent: str | None = None,1022 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1023why, one step back1023 ) -> "Template":Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1024–1026why, one step back1024 """Like :meth:`get_template`, but tries loading multiple names.1025 If none of the names can be loaded a :exc:`TemplatesNotFound`1026 exception is raised.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1027why, one step back1027Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1028–1040why, one step back1028 :param names: List of template names to try loading in order.1029 :param parent: The name of the parent template importing this1030 template. :meth:`join_path` can be used to implement name1031 transformations with this.1032 :param globals: Extend the environment :attr:`globals` with1033 these extra variables available for all renders of this1034 template. If the template has already been loaded and1035 cached, its globals are updated with any new items.10361037 .. versionchanged:: 3.01038 If a template is loaded from cache, ``globals`` will update1039 the template's globals instead of ignoring the new values.1040update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1041why, one step back1041 .. versionchanged:: 2.11Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1042–1043why, one step back1042 If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`1043 is raised instead. If no templates were found and ``names``update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1044–1046why, one step back1044 contains :class:`Undefined`, the message is more helpful.10451046 .. versionchanged:: 2.4Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1047–1048why, one step back1047 If ``names`` contains a :class:`Template` object it is1048 returned unchanged.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1049–1058why, one step back10491050 .. versionadded:: 2.31051 """1052 if isinstance(names, Undefined):1053 names._fail_with_undefined_error()10541055 if not names:1056 raise TemplatesNotFound(1057 message="Tried to select from an empty list of templates."1058 )Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
line 1059why, one step back1059update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1060–1068why, one step back1060 for name in names:1061 if isinstance(name, Template):1062 return name1063 if parent is not None:1064 name = self.join_path(name, parent)1065 try:1066 return self._load_template(name, globals)1067 except (TemplateNotFound, UndefinedError):1068 passMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1069why, one step back1069 raise TemplatesNotFound(names) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1070–1071why, one step back10701071 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1072–1073why, one step back1072 def get_or_select_template(1073 self,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1074why, one step back1074 template_name_or_list: t.Union[str, "Template", list[t.Union[str, "Template"]]],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1075–1076why, one step back1075 parent: str | None = None,1076 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1077why, one step back1077 ) -> "Template":Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1078–1079why, one step back1078 """Use :meth:`select_template` if an iterable of template names1079 is given, or :meth:`get_template` if one name is given.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1080–1088why, one step back10801081 .. versionadded:: 2.31082 """1083 if isinstance(template_name_or_list, (str, Undefined)):1084 return self.get_template(template_name_or_list, parent, globals)1085 elif isinstance(template_name_or_list, Template):1086 return template_name_or_list1087 return self.select_template(template_name_or_list, parent, globals)1088Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1089–1090why, one step back1089 def from_string(1090 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1091–1093why, one step back1091 source: str | nodes.Template,1092 globals: t.MutableMapping[str, t.Any] | None = None,1093 template_class: type["Template"] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1094why, one step back1094 ) -> "Template":Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1095–1104why, one step back1095 """Load a template from a source string without using1096 :attr:`loader`.10971098 :param source: Jinja source to compile into a template.1099 :param globals: Extend the environment :attr:`globals` with1100 these extra variables available for all renders of this1101 template. If the template has already been loaded and1102 cached, its globals are updated with any new items.1103 :param template_class: Return an instance of this1104 :class:`Template` class.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1105why, one step back1105 """Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1106why, one step back1106 gs = self.make_globals(globals)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1107why, one step back1107 cls = template_class or self.template_classMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1108why, one step back1108 return cls.from_code(self, self.compile(source), gs, None)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1109why, one step back1109Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1110why, one step back1110 def make_globals(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1111why, one step back1111 self, d: t.MutableMapping[str, t.Any] | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1112why, one step back1112 ) -> t.MutableMapping[str, t.Any]:Merge pull request #1374 from pallets/docs-globalsDavid Lordbefore adoption1c863d0
lines 1113–1130why, one step back1113 """Make the globals map for a template. Any given template1114 globals overlay the environment :attr:`globals`.11151116 Returns a :class:`collections.ChainMap`. This allows any changes1117 to a template's globals to only affect that template, while1118 changes to the environment's globals are still reflected.1119 However, avoid modifying any globals after a template is loaded.11201121 :param d: Dict of template-specific globals.11221123 .. versionchanged:: 3.01124 Use :class:`collections.ChainMap` to always prevent mutating1125 environment globals.1126 """1127 if d is None:1128 d = {}11291130 return ChainMap(d, self.globals)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1131–1133why, one step back113111321133class Template:Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 1134why, one step back1134 """A compiled template that can be rendered.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1135why, one step back1135Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 1136–1138why, one step back1136 Use the methods on :class:`Environment` to create or load templates.1137 The environment is used to configure how templates are compiled and1138 behave.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1139why, one step back1139Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 1140–1144why, one step back1140 It is also possible to create a template object directly. This is1141 not usually recommended. The constructor takes most of the same1142 arguments as :class:`Environment`. All templates created with the1143 same environment arguments share the same ephemeral ``Environment``1144 instance behind the scenes.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1145why, one step back1145Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 1146–1147why, one step back1146 A template object should be considered immutable. Modifications on1147 the object are not supported.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1148–1151why, one step back1148 """11491150 #: Type of environment to create when creating a template directly1151 #: rather than through an existing environment.Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1152why, one step back1152 environment_class: type[Environment] = Environmentupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1153why, one step back1153Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1154–1155why, one step back1154 environment: Environment1155 globals: t.MutableMapping[str, t.Any]drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1156–1157why, one step back1156 name: str | None1157 filename: str | NoneUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1158why, one step back1158 blocks: dict[str, t.Callable[[Context], t.Iterator[str]]]Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1159–1161why, one step back1159 root_render_func: t.Callable[[Context], t.Iterator[str]]1160 _module: t.Optional["TemplateModule"]1161 _debug_info: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1162why, one step back1162 _uptodate: t.Callable[[], bool] | NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1163why, one step back1163update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1164–1165why, one step back1164 def __new__(1165 cls,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1166why, one step back1166 source: str | nodes.Template,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1167–1172why, one step back1167 block_start_string: str = BLOCK_START_STRING,1168 block_end_string: str = BLOCK_END_STRING,1169 variable_start_string: str = VARIABLE_START_STRING,1170 variable_end_string: str = VARIABLE_END_STRING,1171 comment_start_string: str = COMMENT_START_STRING,1172 comment_end_string: str = COMMENT_END_STRING,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1173–1174why, one step back1173 line_statement_prefix: str | None = LINE_STATEMENT_PREFIX,1174 line_comment_prefix: str | None = LINE_COMMENT_PREFIX,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1175–1178why, one step back1175 trim_blocks: bool = TRIM_BLOCKS,1176 lstrip_blocks: bool = LSTRIP_BLOCKS,1177 newline_sequence: "te.Literal['\\n', '\\r\\n', '\\r']" = NEWLINE_SEQUENCE,1178 keep_trailing_newline: bool = KEEP_TRAILING_NEWLINE,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1179why, one step back1179 extensions: t.Sequence[str | type["Extension"]] = (),Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1180why, one step back1180 optimized: bool = True,Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1181why, one step back1181 undefined: type[Undefined] = Undefined,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1182–1183why, one step back1182 finalize: t.Callable[..., t.Any] | None = None,1183 autoescape: bool | t.Callable[[str | None], bool] = False,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1184why, one step back1184 enable_async: bool = False,Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3
line 1185why, one step back1185 ) -> t.Any: # it returns a `Template`, but this breaks the sphinx build...update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1186why, one step back1186 env = get_spontaneous_environment(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1187why, one step back1187 cls.environment_class, # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1188–1201why, one step back1188 block_start_string,1189 block_end_string,1190 variable_start_string,1191 variable_end_string,1192 comment_start_string,1193 comment_end_string,1194 line_statement_prefix,1195 line_comment_prefix,1196 trim_blocks,1197 lstrip_blocks,1198 newline_sequence,1199 keep_trailing_newline,1200 frozenset(extensions),1201 optimized,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1202why, one step back1202 undefined, # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1203–1213why, one step back1203 finalize,1204 autoescape,1205 None,1206 0,1207 False,1208 None,1209 enable_async,1210 )1211 return env.from_string(source, template_class=cls)12121213 @classmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1214–1218why, one step back1214 def from_code(1215 cls,1216 environment: Environment,1217 code: CodeType,1218 globals: t.MutableMapping[str, t.Any],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1219why, one step back1219 uptodate: t.Callable[[], bool] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1220why, one step back1220 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1221–1230why, one step back1221 """Creates a template object from compiled code and the globals. This1222 is used by the loaders and environment to create a template object.1223 """1224 namespace = {"environment": environment, "__file__": code.co_filename}1225 exec(code, namespace)1226 rv = cls._from_namespace(environment, namespace, globals)1227 rv._uptodate = uptodate1228 return rv12291230 @classmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1231–1236why, one step back1231 def from_module_dict(1232 cls,1233 environment: Environment,1234 module_dict: t.MutableMapping[str, t.Any],1235 globals: t.MutableMapping[str, t.Any],1236 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1237–1244why, one step back1237 """Creates a template object from a module. This is used by the1238 module loader to create a template object.12391240 .. versionadded:: 2.41241 """1242 return cls._from_namespace(environment, module_dict, globals)12431244 @classmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1245–1250why, one step back1245 def _from_namespace(1246 cls,1247 environment: Environment,1248 namespace: t.MutableMapping[str, t.Any],1249 globals: t.MutableMapping[str, t.Any],1250 ) -> "Template":[pre-commit.ci] pre-commit autoupdate (#1993)David Lordbefore adoption9c6c319
line 1251why, one step back1251 t: Template = object.__new__(cls)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1252–1258why, one step back1252 t.environment = environment1253 t.globals = globals1254 t.name = namespace["name"]1255 t.filename = namespace["__file__"]1256 t.blocks = namespace["blocks"]12571258 # render function and moduleMerge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1259why, one step back1259 t.root_render_func = namespace["root"]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1260–1271why, one step back1260 t._module = None12611262 # debug and loader helpers1263 t._debug_info = namespace["debug_info"]1264 t._uptodate = None12651266 # store the reference1267 namespace["environment"] = environment1268 namespace["__jinja_template__"] = t12691270 return t1271Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1272why, one step back1272 def render(self, *args: t.Any, **kwargs: t.Any) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1273–1281why, one step back1273 """This method accepts the same arguments as the `dict` constructor:1274 A dict, a dict subclass or some keyword arguments. If no arguments1275 are given the context will be empty. These two calls do the same::12761277 template.render(knights='that say nih')1278 template.render({'knights': 'that say nih'})12791280 This will return the rendered template as a string.1281 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1282–1284why, one step back1282 if self.environment.is_async:1283 import asyncio1284Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1285why, one step back1285 return asyncio.run(self.render_async(*args, **kwargs))Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1286–1288why, one step back12861287 ctx = self.new_context(dict(*args, **kwargs))1288update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1289why, one step back1289 try:Merge pull request #1511 from mkrizek/issue-1510David Lordbefore adoption7d72eb7
line 1290why, one step back1290 return self.environment.concat(self.root_render_func(ctx)) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1291–1293why, one step back1291 except Exception:1292 self.environment.handle_exception()1293Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1294why, one step back1294 async def render_async(self, *args: t.Any, **kwargs: t.Any) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1295–1302why, one step back1295 """This works similar to :meth:`render` but returns a coroutine1296 that when awaited returns the entire rendered template string. This1297 requires the async feature to be enabled.12981299 Example usage::13001301 await template.render_async(knights='that say nih; asynchronously')1302 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1303–1306why, one step back1303 if not self.environment.is_async:1304 raise RuntimeError(1305 "The environment was not created with async mode enabled."1306 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1307why, one step back1307Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1308–1310why, one step back1308 ctx = self.new_context(dict(*args, **kwargs))13091310 try:Merge pull request #1511 from mkrizek/issue-1510David Lordbefore adoption7d72eb7
lines 1311–1313why, one step back1311 return self.environment.concat( # type: ignore1312 [n async for n in self.root_render_func(ctx)] # type: ignore1313 )Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1314–1316why, one step back1314 except Exception:1315 return self.environment.handle_exception()1316Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1317why, one step back1317 def stream(self, *args: t.Any, **kwargs: t.Any) -> "TemplateStream":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1318–1322why, one step back1318 """Works exactly like :meth:`generate` but returns a1319 :class:`TemplateStream`.1320 """1321 return TemplateStream(self.generate(*args, **kwargs))1322Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1323why, one step back1323 def generate(self, *args: t.Any, **kwargs: t.Any) -> t.Iterator[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1324–1330why, one step back1324 """For very large templates it can be useful to not render the whole1325 template at once but evaluate each statement after another and yield1326 piece for piece. This method basically does exactly that and returns1327 a generator that yields one item after another as strings.13281329 It accepts the same arguments as :meth:`render`.1330 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1331–1333why, one step back1331 if self.environment.is_async:1332 import asyncio1333Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1334why, one step back1334 async def to_list() -> list[str]:Merge branch '3.0.x'David Lordbefore adoptioncdbda09
line 1335why, one step back1335 return [x async for x in self.generate_async(*args, **kwargs)]Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1336why, one step back1336Merge pull request #1534 from pallets/drop-python-3.6David Lordbefore adoptionb2bc7be
line 1337why, one step back1337 yield from asyncio.run(to_list())Merge branch '3.0.x'David Lordbefore adoptioncdbda09
line 1338why, one step back1338 returnMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1339–1341why, one step back13391340 ctx = self.new_context(dict(*args, **kwargs))1341update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1342why, one step back1342 try:Merge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1343why, one step back1343 yield from self.root_render_func(ctx)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1344–1346why, one step back1344 except Exception:1345 yield self.environment.handle_exception()1346Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1347–1348why, one step back1347 async def generate_async(1348 self, *args: t.Any, **kwargs: t.AnyMerge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1349why, one step back1349 ) -> t.AsyncGenerator[str, object]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1350–1352why, one step back1350 """An async version of :meth:`generate`. Works very similarly but1351 returns an async iterator instead.1352 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1353–1356why, one step back1353 if not self.environment.is_async:1354 raise RuntimeError(1355 "The environment was not created with async mode enabled."1356 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1357why, one step back1357Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1358–1360why, one step back1358 ctx = self.new_context(dict(*args, **kwargs))13591360 try:drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1361–1364why, one step back1361 agen: t.AsyncGenerator[str, None] = self.root_render_func(ctx) # type: ignore[assignment]13621363 async with aclosing(agen):1364 async for event in agen:Merge branch '3.1.x'David Lordbefore adoptionb002d9c
line 1365why, one step back1365 yield eventMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1366–1368why, one step back1366 except Exception:1367 yield self.environment.handle_exception()1368Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1369–1370why, one step back1369 def new_context(1370 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1371why, one step back1371 vars: dict[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1372why, one step back1372 shared: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1373why, one step back1373 locals: t.Mapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1374why, one step back1374 ) -> Context:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1375–1385why, one step back1375 """Create a new :class:`Context` for this template. The vars1376 provided will be passed to the template. Per default the globals1377 are added to the context. If shared is set to `True` the data1378 is passed as is to the context without adding the globals.13791380 `locals` can be a dict of local variables for internal usage.1381 """1382 return new_context(1383 self.environment, self.name, self.blocks, vars, shared, self.globals, locals1384 )1385Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1386–1387why, one step back1386 def make_module(1387 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1388why, one step back1388 vars: dict[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1389why, one step back1389 shared: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1390why, one step back1390 locals: t.Mapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1391why, one step back1391 ) -> "TemplateModule":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1392–1397why, one step back1392 """This method works like the :attr:`module` attribute when called1393 without arguments but it will evaluate the template on every call1394 rather than caching it. It's also possible to provide1395 a dict which is then used as context. The arguments are the same1396 as for the :meth:`new_context` method.1397 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1398–1399why, one step back1398 ctx = self.new_context(vars, shared, locals)1399 return TemplateModule(self, ctx)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1400why, one step back1400Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1401–1402why, one step back1401 async def make_module_async(1402 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1403why, one step back1403 vars: dict[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1404why, one step back1404 shared: bool = False,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1405why, one step back1405 locals: t.Mapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1406why, one step back1406 ) -> "TemplateModule":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1407–1411why, one step back1407 """As template module creation can invoke template code for1408 asynchronous executions this method must be used instead of the1409 normal :meth:`make_module` one. Likewise the module attribute1410 becomes unavailable in async mode.1411 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
line 1412why, one step back1412 ctx = self.new_context(vars, shared, locals)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1413why, one step back1413 return TemplateModule(Merge branch '3.1.x'David Lordbefore adoptionde61312
lines 1414–1416why, one step back1414 self,1415 ctx,1416 [x async for x in self.root_render_func(ctx)], # type: ignoreMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1417why, one step back1417 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1418–1419why, one step back14181419 @internalcodedrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1420why, one step back1420 def _get_default_module(self, ctx: Context | None = None) -> "TemplateModule":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1421why, one step back1421 """If a context is passed in, this means that the template wasMerge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1422–1424why, one step back1422 imported. Imported templates have access to the current1423 template's globals by default, but they can only be accessed via1424 the context during runtime.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1425why, one step back1425Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1426–1430why, one step back1426 If there are new globals, we need to create a new module because1427 the cached module is already rendered and will not have access1428 to globals from the current context. This new module is not1429 cached because the template can be imported elsewhere, and it1430 should have access to only the current template's globals.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1431why, one step back1431 """Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1432–1434why, one step back1432 if self.environment.is_async:1433 raise RuntimeError("Module is not available in async mode.")1434update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1435why, one step back1435 if ctx is not None:Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1436–1445why, one step back1436 keys = ctx.globals_keys - self.globals.keys()14371438 if keys:1439 return self.make_module({k: ctx.parent[k] for k in keys})14401441 if self._module is None:1442 self._module = self.make_module()14431444 return self._module1445Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1446why, one step back1446 async def _get_default_module_async(drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1447why, one step back1447 self, ctx: Context | None = NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1448why, one step back1448 ) -> "TemplateModule":Merge pull request #1392 from pallets/inline-asyncDavid Lordbefore adoption9d4689b
lines 1449–1458why, one step back1449 if ctx is not None:1450 keys = ctx.globals_keys - self.globals.keys()14511452 if keys:1453 return await self.make_module_async({k: ctx.parent[k] for k in keys})14541455 if self._module is None:1456 self._module = await self.make_module_async()14571458 return self._moduleupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1459–1460why, one step back14591460 @propertyMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1461why, one step back1461 def module(self) -> "TemplateModule":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1462–1475why, one step back1462 """The template as module. This is used for imports in the1463 template runtime but is also useful if one wants to access1464 exported template variables from the Python layer:14651466 >>> t = Template('{% macro foo() %}42{% endmacro %}23')1467 >>> str(t.module)1468 '23'1469 >>> t.module.foo() == u'42'1470 True14711472 This attribute is not available if async mode is enabled.1473 """1474 return self._get_default_module()1475Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1476why, one step back1476 def get_corresponding_lineno(self, lineno: int) -> int:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1477–1485why, one step back1477 """Return the source line number of a line number in the1478 generated bytecode as they are not in sync.1479 """1480 for template_line, code_line in reversed(self.debug_info):1481 if code_line <= lineno:1482 return template_line1483 return 114841485 @propertyMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1486why, one step back1486 def is_up_to_date(self) -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1487–1492why, one step back1487 """If this variable is `False` there is a newer version available."""1488 if self._uptodate is None:1489 return True1490 return self._uptodate()14911492 @propertyUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1493why, one step back1493 def debug_info(self) -> list[tuple[int, int]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1494–1495why, one step back1494 """The debug info mapping."""1495 if self._debug_info:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1496–1500why, one step back1496 return [1497 tuple(map(int, x.split("="))) # type: ignore1498 for x in self._debug_info.split("&")1499 ]1500update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1501–1502why, one step back1501 return []1502Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1503why, one step back1503 def __repr__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1504–1507why, one step back1504 if self.name is None:1505 name = f"memory:{id(self):x}"1506 else:1507 name = repr(self.name)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1508why, one step back1508 return f"<{type(self).__name__} {name}>"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1509–1516why, one step back150915101511class TemplateModule:1512 """Represents an imported template. All the exported names of the1513 template are available as attributes on this object. Additionally1514 converting it into a string renders the contents.1515 """1516Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1517–1520why, one step back1517 def __init__(1518 self,1519 template: Template,1520 context: Context,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1521why, one step back1521 body_stream: t.Iterable[str] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1522why, one step back1522 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1523–1525why, one step back1523 if body_stream is None:1524 if context.environment.is_async:1525 raise RuntimeError(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1526–1528why, one step back1526 "Async mode requires a body stream to be passed to"1527 " a template module. Use the async methods of the"1528 " API you are using."update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1529why, one step back1529 )Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1530why, one step back1530Merge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1531why, one step back1531 body_stream = list(template.root_render_func(context))Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1532why, one step back1532update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1533–1536why, one step back1533 self._body_stream = body_stream1534 self.__dict__.update(context.get_exported())1535 self.__name__ = template.name1536Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1537why, one step back1537 def __html__(self) -> Markup:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1538–1539why, one step back1538 return Markup(concat(self._body_stream))1539Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1540why, one step back1540 def __str__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1541–1542why, one step back1541 return concat(self._body_stream)1542Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1543why, one step back1543 def __repr__(self) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1544–1547why, one step back1544 if self.__name__ is None:1545 name = f"memory:{id(self):x}"1546 else:1547 name = repr(self.__name__)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1548why, one step back1548 return f"<{type(self).__name__} {name}>"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1549–1556why, one step back154915501551class TemplateExpression:1552 """The :meth:`jinja2.Environment.compile_expression` method returns an1553 instance of this object. It encapsulates the expression-like access1554 to the template with an expression it wraps.1555 """1556Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1557why, one step back1557 def __init__(self, template: Template, undefined_to_none: bool) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1558–1560why, one step back1558 self._template = template1559 self._undefined_to_none = undefined_to_none1560drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 1561why, one step back1561 def __call__(self, *args: t.Any, **kwargs: t.Any) -> t.Any | None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1562why, one step back1562 context = self._template.new_context(dict(*args, **kwargs))Merge branch '3.1.x'David Lordbefore adoption5d9ece6
line 1563why, one step back1563 consume(self._template.root_render_func(context))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1564–1580why, one step back1564 rv = context.vars["result"]1565 if self._undefined_to_none and isinstance(rv, Undefined):1566 rv = None1567 return rv156815691570class TemplateStream:1571 """A template stream works pretty much like an ordinary python generator1572 but it can buffer multiple items to reduce the number of total iterations.1573 Per default the output is unbuffered which means that for every unbuffered1574 instruction in the template one string is yielded.15751576 If buffering is enabled with a buffer size of 5, five items are combined1577 into a new string. This is mainly useful if you are streaming1578 big templates to a client via WSGI which flushes after each iteration.1579 """1580Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1581why, one step back1581 def __init__(self, gen: t.Iterator[str]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1582–1584why, one step back1582 self._gen = gen1583 self.disable_buffering()1584Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1585–1586why, one step back1585 def dump(1586 self,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
lines 1587–1589why, one step back1587 fp: str | t.IO[bytes],1588 encoding: str | None = None,1589 errors: str | None = "strict",Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1590why, one step back1590 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1591–1599why, one step back1591 """Dump the complete stream into a file or file-like object.1592 Per default strings are written, if you want to encode1593 before writing specify an `encoding`.15941595 Example usage::15961597 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1598 """1599 close = FalseMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1600why, one step back1600update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1601–1603why, one step back1601 if isinstance(fp, str):1602 if encoding is None:1603 encoding = "utf-8"Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1604why, one step back1604Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1605why, one step back1605 real_fp: t.IO[bytes] = open(fp, "wb")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1606why, one step back1606 close = TrueMerge branch '3.1.x'David Lordbefore adoptionde61312
lines 1607–1609why, one step back1607 else:1608 real_fp = fp1609update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1610–1611why, one step back1610 try:1611 if encoding is not None:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1612why, one step back1612 iterable = (x.encode(encoding, errors) for x in self) # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1613why, one step back1613 else:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1614–1615why, one step back1614 iterable = self # type: ignore1615Merge branch '3.1.x'David Lordbefore adoptionde61312
lines 1616–1617why, one step back1616 if hasattr(real_fp, "writelines"):1617 real_fp.writelines(iterable)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1618–1619why, one step back1618 else:1619 for item in iterable:Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1620why, one step back1620 real_fp.write(item)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1621–1622why, one step back1621 finally:1622 if close:Merge branch '3.1.x'David Lordbefore adoptionde61312
line 1623why, one step back1623 real_fp.close()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 1624why, one step back1624Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1625why, one step back1625 def disable_buffering(self) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1626–1629why, one step back1626 """Disable the output buffering."""1627 self._next = partial(next, self._gen)1628 self.buffered = False1629Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1630why, one step back1630 def _buffered_generator(self, size: int) -> t.Iterator[str]:Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 1631why, one step back1631 buf: list[str] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1632–1634why, one step back1632 c_size = 01633 push = buf.append1634Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1635why, one step back1635 while True:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1636–1648why, one step back1636 try:1637 while c_size < size:1638 c = next(self._gen)1639 push(c)1640 if c:1641 c_size += 11642 except StopIteration:1643 if not c_size:1644 return1645 yield concat(buf)1646 del buf[:]1647 c_size = 01648Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1649why, one step back1649 def enable_buffering(self, size: int = 5) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1650–1656why, one step back1650 """Enable buffering. Buffer `size` items before yielding them."""1651 if size <= 1:1652 raise ValueError("buffer size too small")16531654 self.buffered = True1655 self._next = partial(next, self._buffered_generator(size))1656Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 1657why, one step back1657 def __iter__(self) -> "TemplateStream":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1658–1659why, one step back1658 return self1659Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 1660–1661why, one step back1660 def __next__(self) -> str:1661 return self._next() # type: ignoreupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1662–1666why, one step back166216631664# hook in default template class. if anyone reads this comment: ignore that1665# it's possible to use custom templates ;-)1666Environment.template_class = Template