Like :meth:`get_template`, but tries loading multiple names. If none of the names can be loaded a :exc:`TemplatesNotFound` exception is raised. :param names: List of template names to try loading in order. :param parent: The name of the parent template importing this
(
self,
names: t.Iterable[t.Union[str, "Template"]],
parent: t.Optional[str] = None,
globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
)
| 1017 | |
| 1018 | @internalcode |
| 1019 | def select_template( |
| 1020 | self, |
| 1021 | names: t.Iterable[t.Union[str, "Template"]], |
| 1022 | parent: t.Optional[str] = None, |
| 1023 | globals: t.Optional[t.MutableMapping[str, t.Any]] = None, |
| 1024 | ) -> "Template": |
| 1025 | """Like :meth:`get_template`, but tries loading multiple names. |
| 1026 | If none of the names can be loaded a :exc:`TemplatesNotFound` |
| 1027 | exception is raised. |
| 1028 | |
| 1029 | :param names: List of template names to try loading in order. |
| 1030 | :param parent: The name of the parent template importing this |
| 1031 | template. :meth:`join_path` can be used to implement name |
| 1032 | transformations with this. |
| 1033 | :param globals: Extend the environment :attr:`globals` with |
| 1034 | these extra variables available for all renders of this |
| 1035 | template. If the template has already been loaded and |
| 1036 | cached, its globals are updated with any new items. |
| 1037 | |
| 1038 | .. versionchanged:: 3.0 |
| 1039 | If a template is loaded from cache, ``globals`` will update |
| 1040 | the template's globals instead of ignoring the new values. |
| 1041 | |
| 1042 | .. versionchanged:: 2.11 |
| 1043 | If ``names`` is :class:`Undefined`, an :exc:`UndefinedError` |
| 1044 | is raised instead. If no templates were found and ``names`` |
| 1045 | contains :class:`Undefined`, the message is more helpful. |
| 1046 | |
| 1047 | .. versionchanged:: 2.4 |
| 1048 | If ``names`` contains a :class:`Template` object it is |
| 1049 | returned unchanged. |
| 1050 | |
| 1051 | .. versionadded:: 2.3 |
| 1052 | """ |
| 1053 | if isinstance(names, Undefined): |
| 1054 | names._fail_with_undefined_error() |
| 1055 | |
| 1056 | if not names: |
| 1057 | raise TemplatesNotFound( |
| 1058 | message="Tried to select from an empty list of templates." |
| 1059 | ) |
| 1060 | |
| 1061 | for name in names: |
| 1062 | if isinstance(name, Template): |
| 1063 | return name |
| 1064 | if parent is not None: |
| 1065 | name = self.join_path(name, parent) |
| 1066 | try: |
| 1067 | return self._load_template(name, globals) |
| 1068 | except (TemplateNotFound, UndefinedError): |
| 1069 | pass |
| 1070 | raise TemplatesNotFound(names) # type: ignore |
| 1071 | |
| 1072 | @internalcode |
| 1073 | def get_or_select_template( |