Skip to content
Myr

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

4 files+137 added−76 removed

modified:docs/api.rst+39 added-13 removed
112 unmodified lines
113 :ref:`identifier-naming`.114115 .. attribute:: globals116117 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`.121122 .. attribute:: policies123124 A dictionary with :ref:`policies`. These can be reconfigured to
54 unmodified lines
179 :members: module, make_module180181 .. attribute:: globals182183 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.188189 Defaults to :attr:`Environment.globals` unless extra values are190 passed to :meth:`Environment.get_template`.191192 Globals are only intended for data that is common to every193 render of the template. Specific data should be passed to194 :meth:`render`.195196 See :ref:`global-namespace`.197198 .. attribute:: name199200 The loading name of the template. If the template was loaded from a201 string this is `None`.
622 unmodified lines
824825The Global Namespace826--------------------827817Variables stored in the :attr:`Environment.globals` dict are special as they818are available for imported templates too, even if they are imported without819context. This is the place where you can put variables and functions820that should be available all the time. Additionally :attr:`Template.globals`821exist that are variables available to a specific template that are available822to all :meth:`~Template.render` calls.828The global namespace stores variables and functions that should be829available without needing to pass them to :meth:`Template.render`. They830are also available to templates that are imported or included without831context. Most applications should only use :attr:`Environment.globals`.832833:attr:`Environment.globals` are intended for data that is common to all834templates loaded by that environment. :attr:`Template.globals` are835intended for data that is common to all renders of that template, and836default to :attr:`Environment.globals` unless they're given in837:meth:`Environment.get_template`, etc. Data that is specific to a838render should be passed as context to :meth:`Template.render`.839840Only one set of globals is used during any specific rendering. If841templates A and B both have template globals, and B extends A, then842only B's globals are used for both when using ``b.render()``.843844Environment globals should not be changed after loading any templates,845and template globals should not be changed at any time after loading the846template. Changing globals after loading a template will result in847unexpected behavior as they may be shared between the environment and848other templates.849850851.. _low-level-api:852853Low Level API854-------------
57 unmodified lines
modified:src/jinja2/environment.py+78 added-39 removed
3 unmodified lines
4import os5import sys6import typing as t7import weakref8from collections import ChainMap9from functools import partial10from functools import reduce1112from markupsafe import Markup
798 unmodified lines
811 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)819820 return template821825 template = self.loader.load(self, name, globals)822 template = self.loader.load(self, name, self.make_globals(globals))823824 if self.cache is not None:825 self.cache[cache_key] = template826 return template827828 @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.833837 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.842840 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.846847 .. 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))855856 return self._load_template(name, globals)857858 @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.863864 :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.872873 .. versionchanged:: 3.0874 If a template is loaded from cache, ``globals`` will update875 the template's globals instead of ignoring the new values.876877 .. 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.881882 .. 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.885886 .. versionadded:: 2.3887 """888 if isinstance(names, Undefined):
2 unmodified lines
891 if not names:892 raise TemplatesNotFound(893 message="Tried to select from an empty list of templates."894 )877 globals = self.make_globals(globals)895896 for name in names:897 if isinstance(name, Template):898 return name899 if parent is not None:
5 unmodified lines
905 raise TemplatesNotFound(names)906907 @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.911912 .. versionadded:: 2.3913 """914 if isinstance(template_name_or_list, (str, Undefined)):
2 unmodified lines
917 return template_name_or_list918 return self.select_template(template_name_or_list, parent, globals)919920 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`.923924 :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)935936 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`.939940 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.944945 :param d: Dict of template-specific globals.946947 .. versionchanged:: 3.0948 Use :class:`collections.ChainMap` to always prevent mutating949 environment globals.950 """951 if d is None:952 d = {}953954 return ChainMap(d, self.globals)955956957class Template:958 """The central template object. This class represents a compiled template959 and is used to evaluate it.960
423 unmodified lines
modified:tests/test_regression.py+17 added-22 removed
715 unmodified lines
716 # 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"719720 @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"729730 # 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"733734 # 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"737738 # 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"741738 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"744745 tmpl = env.get_template("base", globals={"foo": 42})746 assert tmpl.render() == "42"747742 # 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"745746 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 lines
35- 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`424344Version 2.11.345--------------
780 unmodified lines