Skip to content

Commit 0f793b9

Browse files
committed
Make TemplateContext typed, move utils.filters to utils.templates
1 parent 73e5039 commit 0f793b9

File tree

7 files changed

+73
-35
lines changed

7 files changed

+73
-35
lines changed

docs/dev-guide/api.md

+5
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,11 @@ NOTE: The main entry point to the API is through [Events](plugins.md#events) tha
1414
options:
1515
show_root_heading: true
1616

17+
::: mkdocs.utils.templates.TemplateContext
18+
options:
19+
show_root_heading: true
20+
show_if_no_docstring: true
21+
1722
::: mkdocs.livereload.LiveReloadServer
1823
options:
1924
show_root_heading: true

mkdocs/commands/build.py

+14-13
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import logging
55
import os
66
import time
7-
from typing import TYPE_CHECKING, Any, Sequence
7+
from typing import TYPE_CHECKING, Sequence
88
from urllib.parse import urlsplit
99

1010
import jinja2
@@ -15,6 +15,7 @@
1515
from mkdocs.exceptions import Abort, BuildError
1616
from mkdocs.structure.files import File, Files, get_files
1717
from mkdocs.structure.nav import Navigation, get_navigation
18+
from mkdocs.utils import templates
1819

1920
if TYPE_CHECKING:
2021
from mkdocs.config.defaults import MkDocsConfig
@@ -43,7 +44,7 @@ def get_context(
4344
config: MkDocsConfig,
4445
page: Page | None = None,
4546
base_url: str = '',
46-
) -> dict[str, Any]:
47+
) -> templates.TemplateContext:
4748
"""
4849
Return the template context for a given page or template.
4950
"""
@@ -57,17 +58,17 @@ def get_context(
5758
if isinstance(files, Files):
5859
files = files.documentation_pages()
5960

60-
return {
61-
'nav': nav,
62-
'pages': files,
63-
'base_url': base_url,
64-
'extra_css': extra_css,
65-
'extra_javascript': extra_javascript,
66-
'mkdocs_version': mkdocs.__version__,
67-
'build_date_utc': utils.get_build_datetime(),
68-
'config': config,
69-
'page': page,
70-
}
61+
return templates.TemplateContext(
62+
nav=nav,
63+
pages=files,
64+
base_url=base_url,
65+
extra_css=extra_css,
66+
extra_javascript=extra_javascript,
67+
mkdocs_version=mkdocs.__version__,
68+
build_date_utc=utils.get_build_datetime(),
69+
config=config,
70+
page=page,
71+
)
7172

7273

7374
def _build_template(

mkdocs/contrib/search/__init__.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import logging
44
import os
5-
from typing import TYPE_CHECKING, Any, List
5+
from typing import TYPE_CHECKING, List
66

77
from mkdocs import utils
88
from mkdocs.config import base
@@ -12,6 +12,7 @@
1212

1313
if TYPE_CHECKING:
1414
from mkdocs.config.defaults import MkDocsConfig
15+
from mkdocs.util.templates import TemplateContext
1516

1617
log = logging.getLogger(__name__)
1718
base_path = os.path.dirname(os.path.abspath(__file__))
@@ -85,7 +86,7 @@ def on_pre_build(self, config: MkDocsConfig, **kwargs) -> None:
8586
"Create search index instance for later use."
8687
self.search_index = SearchIndex(**self.config)
8788

88-
def on_page_context(self, context: dict[str, Any], **kwargs) -> None:
89+
def on_page_context(self, context: TemplateContext, **kwargs) -> None:
8990
"Add page to search index."
9091
self.search_index.add_entry_from_context(context['page'])
9192

mkdocs/plugins.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
from mkdocs.structure.files import Files
3131
from mkdocs.structure.nav import Navigation
3232
from mkdocs.structure.pages import Page
33+
from mkdocs.utils.templates import TemplateContext
3334

3435

3536
log = logging.getLogger('mkdocs.plugins')
@@ -267,8 +268,8 @@ def on_pre_template(
267268
return template
268269

269270
def on_template_context(
270-
self, context: dict[str, Any], *, template_name: str, config: MkDocsConfig
271-
) -> dict[str, Any] | None:
271+
self, context: TemplateContext, *, template_name: str, config: MkDocsConfig
272+
) -> TemplateContext | None:
272273
"""
273274
The `template_context` event is called immediately after the context is created
274275
for the subject template and can be used to alter the context for that specific
@@ -374,8 +375,8 @@ def on_page_content(
374375
return html
375376

376377
def on_page_context(
377-
self, context: dict[str, Any], *, page: Page, config: MkDocsConfig, nav: Navigation
378-
) -> dict[str, Any] | None:
378+
self, context: TemplateContext, *, page: Page, config: MkDocsConfig, nav: Navigation
379+
) -> TemplateContext | None:
379380
"""
380381
The `page_context` event is called after the context for a page is created
381382
and can be used to alter the context for that specific page only.

mkdocs/theme.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88

99
from mkdocs import localization, utils
1010
from mkdocs.config.base import ValidationError
11-
from mkdocs.utils import filters
11+
from mkdocs.utils import templates
1212

1313
log = logging.getLogger(__name__)
1414

@@ -116,6 +116,6 @@ def get_env(self) -> jinja2.Environment:
116116
loader = jinja2.FileSystemLoader(self.dirs)
117117
# No autoreload because editing a template in the middle of a build is not useful.
118118
env = jinja2.Environment(loader=loader, auto_reload=False)
119-
env.filters['url'] = filters.url_filter
119+
env.filters['url'] = templates.url_filter
120120
localization.install_translations(env, self._vars['locale'], self.dirs)
121121
return env

mkdocs/utils/filters.py

+1-14
Original file line numberDiff line numberDiff line change
@@ -1,14 +1 @@
1-
from __future__ import annotations
2-
3-
try:
4-
from jinja2 import pass_context as contextfilter # type: ignore
5-
except ImportError:
6-
from jinja2 import contextfilter # type: ignore
7-
8-
from mkdocs.utils import normalize_url
9-
10-
11-
@contextfilter
12-
def url_filter(context, value: str) -> str:
13-
"""A Template filter to normalize URLs."""
14-
return normalize_url(value, page=context['page'], base=context['base_url'])
1+
from .templates import url_filter # noqa - legacy re-export

mkdocs/utils/templates.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
from __future__ import annotations
2+
3+
import sys
4+
from typing import TYPE_CHECKING, Sequence
5+
6+
if sys.version_info >= (3, 8):
7+
from typing import TypedDict
8+
else:
9+
from typing_extensions import TypedDict
10+
11+
if TYPE_CHECKING:
12+
import datetime
13+
14+
try:
15+
from jinja2 import pass_context as contextfilter # type: ignore
16+
except ImportError:
17+
from jinja2 import contextfilter # type: ignore
18+
19+
from mkdocs.utils import normalize_url
20+
21+
if TYPE_CHECKING:
22+
from mkdocs.config.defaults import MkDocsConfig
23+
from mkdocs.structure.files import File
24+
from mkdocs.structure.nav import Navigation
25+
from mkdocs.structure.pages import Page
26+
27+
28+
class TemplateContext(TypedDict):
29+
nav: Navigation
30+
pages: Sequence[File]
31+
base_url: str
32+
extra_css: Sequence[str]
33+
extra_javascript: Sequence[str]
34+
mkdocs_version: str
35+
build_date_utc: datetime.datetime
36+
config: MkDocsConfig
37+
page: Page | None
38+
39+
40+
@contextfilter
41+
def url_filter(context: TemplateContext, value: str) -> str:
42+
"""A Template filter to normalize URLs."""
43+
return normalize_url(value, page=context['page'], base=context['base_url'])

0 commit comments

Comments
 (0)