| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING, Sequence, TypedDict |
| 4 |
|
| 5 |
if TYPE_CHECKING: |
| 6 |
import datetime |
| 7 |
|
| 8 |
from markupsafe import Markup |
| 9 |
|
| 10 |
try: |
| 11 |
from jinja2 import pass_context as contextfilter # type: ignore |
| 12 |
except ImportError: |
| 13 |
from jinja2 import contextfilter # type: ignore |
| 14 |
|
| 15 |
from mkdocs.utils import normalize_url |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from mkdocs.config.config_options import ExtraScriptValue |
| 19 |
from mkdocs.config.defaults import MkDocsConfig |
| 20 |
from mkdocs.structure.files import File |
| 21 |
from mkdocs.structure.nav import Navigation |
| 22 |
from mkdocs.structure.pages import Page |
| 23 |
|
| 24 |
|
| 25 |
class TemplateContext(TypedDict): |
| 26 |
nav: Navigation |
| 27 |
pages: Sequence[File] |
| 28 |
base_url: str |
| 29 |
extra_css: Sequence[str] # Do not use, prefer `config.extra_css`. |
| 30 |
extra_javascript: Sequence[str] # Do not use, prefer `config.extra_javascript`. |
| 31 |
mkdocs_version: str |
| 32 |
build_date_utc: datetime.datetime |
| 33 |
config: MkDocsConfig |
| 34 |
page: Page | None |
| 35 |
|
| 36 |
|
| 37 |
@contextfilter |
| 38 |
def url_filter(context: TemplateContext, value: str) -> str: |
| 39 |
"""A Template filter to normalize URLs.""" |
| 40 |
return normalize_url(str(value), page=context['page'], base=context['base_url']) |
| 41 |
|
| 42 |
|
| 43 |
@contextfilter |
| 44 |
def script_tag_filter(context: TemplateContext, extra_script: ExtraScriptValue) -> str: |
| 45 |
"""Converts an ExtraScript value to an HTML <script> tag line.""" |
| 46 |
html = '<script src="{0}"' |
| 47 |
if not isinstance(extra_script, str): |
| 48 |
if extra_script.type: |
| 49 |
html += ' type="{1.type}"' |
| 50 |
if extra_script.defer: |
| 51 |
html += ' defer' |
| 52 |
if extra_script.async_: |
| 53 |
html += ' async' |
| 54 |
html += '></script>' |
| 55 |
return Markup(html).format(url_filter(context, str(extra_script)), extra_script) |