more detailed docs about globals
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 40a312e · Browse files · 4 files·+137 added−76 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+137 added−76 removed
- tests:+17 added−22 removed
- other:+120 added−54 removed
Provenance
- Commit
38e45fe- Tree
213f237- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
40a312e
4 files changed+137 added−76 removed
modified:docs/api.rst+39 added-13 removed
112 unmodified lines113 :ref:`identifier-naming`.114 115 .. attribute:: globals116 117- A dict of global variables. These variables are always available118- in a template. As long as no template was loaded it's safe119- to modify this dict. For more details see :ref:`global-namespace`.120- For valid object names have a look at :ref:`identifier-naming`.117+ A dict of variables that are available in every template loaded118+ by the environment. As long as no template was loaded it's safe119+ to modify this. For more details see :ref:`global-namespace`.120+ For valid object names see :ref:`identifier-naming`.121 122 .. attribute:: policies123 124 A dictionary with :ref:`policies`. These can be reconfigured to54 unmodified lines179 :members: module, make_module180 181 .. attribute:: globals182 183- The dict with the globals of that template. It's unsafe to modify184- this dict as it may be shared with other templates or the environment185- that loaded the template.183+ A dict of variables that are available every time the template184+ is rendered, without needing to pass them during render. This185+ should not be modified, as depending on how the template was186+ loaded it may be shared with the environment and other187+ templates.188 189+ Defaults to :attr:`Environment.globals` unless extra values are190+ passed to :meth:`Environment.get_template`.191+192+ Globals are only intended for data that is common to every193+ render of the template. Specific data should be passed to194+ :meth:`render`.195+196+ See :ref:`global-namespace`.197+198 .. attribute:: name199 200 The loading name of the template. If the template was loaded from a201 string this is `None`.622 unmodified lines824 825 The Global Namespace826 --------------------827 817-Variables stored in the :attr:`Environment.globals` dict are special as they818-are available for imported templates too, even if they are imported without819-context. This is the place where you can put variables and functions820-that should be available all the time. Additionally :attr:`Template.globals`821-exist that are variables available to a specific template that are available822-to all :meth:`~Template.render` calls.828+The global namespace stores variables and functions that should be829+available without needing to pass them to :meth:`Template.render`. They830+are also available to templates that are imported or included without831+context. Most applications should only use :attr:`Environment.globals`.832 833+:attr:`Environment.globals` are intended for data that is common to all834+templates loaded by that environment. :attr:`Template.globals` are835+intended for data that is common to all renders of that template, and836+default to :attr:`Environment.globals` unless they're given in837+:meth:`Environment.get_template`, etc. Data that is specific to a838+render should be passed as context to :meth:`Template.render`.839 840+Only one set of globals is used during any specific rendering. If841+templates A and B both have template globals, and B extends A, then842+only B's globals are used for both when using ``b.render()``.843+844+Environment globals should not be changed after loading any templates,845+and template globals should not be changed at any time after loading the846+template. Changing globals after loading a template will result in847+unexpected behavior as they may be shared between the environment and848+other templates.849+850+851 .. _low-level-api:852 853 Low Level API854 -------------57 unmodified linesmodified:src/jinja2/environment.py+78 added-39 removed
3 unmodified lines4 import os5 import sys6 import typing as t7 import weakref8+from collections import ChainMap9 from functools import partial10 from functools import reduce11 12 from markupsafe import Markup798 unmodified lines811 template = self.cache.get(cache_key)812 if template is not None and (813 not self.auto_reload or template.is_up_to_date814 ):814- # update globals if changed815- new_globals = globals.items() - template.globals.items()816- if new_globals:817- # it is possible for the template and environment to share818- # a globals object, in which case, a new copy should be819- # made to avoid affecting other templates820- if template.globals is self.globals:821- template.globals = dict(template.globals, **globals)822- else:823- template.globals.update(dict(new_globals))815+ # template.globals is a ChainMap, modifying it will only816+ # affect the template, not the environment globals.817+ if globals:818+ template.globals.update(globals)819+820 return template821+825- template = self.loader.load(self, name, globals)822+ template = self.loader.load(self, name, self.make_globals(globals))823+824 if self.cache is not None:825 self.cache[cache_key] = template826 return template827 828 @internalcode829 def get_template(self, name, parent=None, globals=None):832- """Load a template from the loader. If a loader is configured this833- method asks the loader for the template and returns a :class:`Template`.834- If the `parent` parameter is not `None`, :meth:`join_path` is called835- to get the real template name before loading.830+ """Load a template by name with :attr:`loader` and return a831+ :class:`Template`. If the template does not exist a832+ :exc:`TemplateNotFound` exception is raised.833 837- The `globals` parameter can be used to provide template wide globals.838- These variables are available in the context at render time.834+ :param name: Name of the template to load.835+ :param parent: The name of the parent template importing this836+ template. :meth:`join_path` can be used to implement name837+ transformations with this.838+ :param globals: Extend the environment :attr:`globals` with839+ these extra variables available for all renders of this840+ template. If the template has already been loaded and841+ cached, its globals are updated with any new items.842 840- If the template does not exist a :exc:`TemplateNotFound` exception is841- raised.843+ .. versionchanged:: 3.0844+ If a template is loaded from cache, ``globals`` will update845+ the template's globals instead of ignoring the new values.846 847 .. versionchanged:: 2.4844- If `name` is a :class:`Template` object it is returned from the845- function unchanged.848+ If ``name`` is a :class:`Template` object it is returned849+ unchanged.850 """851 if isinstance(name, Template):852 return name853 if parent is not None:854 name = self.join_path(name, parent)851- return self._load_template(name, self.make_globals(globals))855 856+ return self._load_template(name, globals)857+858 @internalcode859 def select_template(self, names, parent=None, globals=None):855- """Works like :meth:`get_template` but tries a number of templates856- before it fails. If it cannot find any of the templates, it will857- raise a :exc:`TemplatesNotFound` exception.860+ """Like :meth:`get_template`, but tries loading multiple names.861+ If none of the names can be loaded a :exc:`TemplatesNotFound`862+ exception is raised.863 864+ :param names: List of template names to try loading in order.865+ :param parent: The name of the parent template importing this866+ template. :meth:`join_path` can be used to implement name867+ transformations with this.868+ :param globals: Extend the environment :attr:`globals` with869+ these extra variables available for all renders of this870+ template. If the template has already been loaded and871+ cached, its globals are updated with any new items.872+873+ .. versionchanged:: 3.0874+ If a template is loaded from cache, ``globals`` will update875+ the template's globals instead of ignoring the new values.876+877 .. versionchanged:: 2.11860- If names is :class:`Undefined`, an :exc:`UndefinedError` is861- raised instead. If no templates were found and names878+ If ``names`` is :class:`Undefined`, an :exc:`UndefinedError`879+ is raised instead. If no templates were found and ``names``880 contains :class:`Undefined`, the message is more helpful.881 882 .. versionchanged:: 2.4865- If `names` contains a :class:`Template` object it is returned866- from the function unchanged.883+ If ``names`` contains a :class:`Template` object it is884+ returned unchanged.885 886 .. versionadded:: 2.3887 """888 if isinstance(names, Undefined):2 unmodified lines891 if not names:892 raise TemplatesNotFound(893 message="Tried to select from an empty list of templates."894 )877- globals = self.make_globals(globals)895+896 for name in names:897 if isinstance(name, Template):898 return name899 if parent is not None:5 unmodified lines905 raise TemplatesNotFound(names)906 907 @internalcode908 def get_or_select_template(self, template_name_or_list, parent=None, globals=None):891- """Does a typecheck and dispatches to :meth:`select_template`892- if an iterable of template names is given, otherwise to893- :meth:`get_template`.909+ """Use :meth:`select_template` if an iterable of template names910+ is given, or :meth:`get_template` if one name is given.911 912 .. versionadded:: 2.3913 """914 if isinstance(template_name_or_list, (str, Undefined)):2 unmodified lines917 return template_name_or_list918 return self.select_template(template_name_or_list, parent, globals)919 920 def from_string(self, source, globals=None, template_class=None):904- """Load a template from a string. This parses the source given and905- returns a :class:`Template` object.921+ """Load a template from a source string without using922+ :attr:`loader`.923+924+ :param source: Jinja source to compile into a template.925+ :param globals: Extend the environment :attr:`globals` with926+ these extra variables available for all renders of this927+ template. If the template has already been loaded and928+ cached, its globals are updated with any new items.929+ :param template_class: Return an instance of this930+ :class:`Template` class.931 """932 globals = self.make_globals(globals)933 cls = template_class or self.template_class934 return cls.from_code(self, self.compile(source), globals, None)935 936 def make_globals(self, d):912- """Return a dict for the globals."""913- if not d:914- return self.globals915- return dict(self.globals, **d)937+ """Make the globals map for a template. Any given template938+ globals overlay the environment :attr:`globals`.939 940+ Returns a :class:`collections.ChainMap`. This allows any changes941+ to a template's globals to only affect that template, while942+ changes to the environment's globals are still reflected.943+ However, avoid modifying any globals after a template is loaded.944 945+ :param d: Dict of template-specific globals.946+947+ .. versionchanged:: 3.0948+ Use :class:`collections.ChainMap` to always prevent mutating949+ environment globals.950+ """951+ if d is None:952+ d = {}953+954+ return ChainMap(d, self.globals)955+956+957 class Template:958 """The central template object. This class represents a compiled template959 and is used to evaluate it.960 423 unmodified linesmodified:tests/test_regression.py+17 added-22 removed
715 unmodified lines716 # values set within a block or loop should not717 # show up outside of it718 assert tmpl.render() == "42\n0\n24\n0\n42\n1\n24\n1\n42"719 720+ @pytest.mark.parametrize("op", ["extends", "include"])720- def test_cached_extends(self):721+ def test_cached_extends(self, op):722 env = Environment(723 loader=DictLoader(723- {"parent": "{{ foo }}", "child": "{% extends 'parent' %}"}724+ {"base": "{{ x }} {{ y }}", "main": f"{{% {op} 'base' %}}"}725 )726 )726- tmpl = env.get_template("child", globals={"foo": "bar"})727- assert tmpl.render() == "bar"727+ env.globals["x"] = "x"728+ env.globals["y"] = "y"729 730+ # template globals overlay env globals729- tmpl = env.get_template("parent", globals={"foo": 42})730- assert tmpl.render() == "42"731+ tmpl = env.get_template("main", globals={"x": "bar"})732+ assert tmpl.render() == "bar y"733 734+ # base was loaded indirectly, it just has env globals732- tmpl = env.get_template("child")733- assert tmpl.render() == "bar"735+ tmpl = env.get_template("base")736+ assert tmpl.render() == "x y"737 738+ # set template globals for base, no longer uses env globals735- tmpl = env.get_template("parent")736- assert tmpl.render() == "42"739+ tmpl = env.get_template("base", globals={"x": 42})740+ assert tmpl.render() == "42 y"741 738- def test_cached_includes(self):739- env = Environment(740- loader=DictLoader({"base": "{{ foo }}", "main": "{% include 'base' %}"})741- )742- tmpl = env.get_template("main", globals={"foo": "bar"})743- assert tmpl.render() == "bar"744-745- tmpl = env.get_template("base", globals={"foo": 42})746- assert tmpl.render() == "42"747-742+ # templates are cached, they keep template globals set earlier743 tmpl = env.get_template("main")749- assert tmpl.render() == "bar"744+ assert tmpl.render() == "bar y"745 746 tmpl = env.get_template("base")752- assert tmpl.render() == "42"747+ assert tmpl.render() == "42 y"modified:CHANGES.rst+3 added-2 removed
34 unmodified lines35 - Fix a bug that prevented variables set in blocks or loops from36 being accessed in custom context functions. :issue:`768`37 - Fix a bug that caused scoped blocks from accessing special loop38 variables. :issue:`1088`39-- Fix a bug that prevented cached templates from registering new globals.40- :issue:`295`39+- Update the template globals when calling40+ ``Environment.get_template(globals=...)`` even if the template was41+ already loaded. :issue:`295`42 43 44 Version 2.11.345 --------------780 unmodified lines