Skip to content

Commit

Permalink
feat: Add option to allow overriding of templates.
Browse files Browse the repository at this point in the history
  • Loading branch information
Holt59 committed Apr 11, 2020
1 parent e378e56 commit 7360021
Show file tree
Hide file tree
Showing 4 changed files with 30 additions and 8 deletions.
4 changes: 3 additions & 1 deletion src/mkdocstrings/extension.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,9 @@ def run(self, parent: Element, blocks: Element) -> None:

handler_name = self.get_handler_name(config)
log.debug(f"mkdocstrings.extension: Using handler '{handler_name}'")
handler = get_handler(handler_name, self._config["theme_name"])
handler = get_handler(handler_name,
self._config["theme_name"],
self._config["mkdocstrings"]["custom_templates"])

selection, rendering = self.get_item_configs(handler_name, config)

Expand Down
25 changes: 20 additions & 5 deletions src/mkdocstrings/handlers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
import importlib
import textwrap
from pathlib import Path
from typing import Sequence, Type
from typing import Sequence, Type, Optional

from jinja2 import Environment, FileSystemLoader
from jinja2.filters import do_mark_safe
Expand Down Expand Up @@ -100,7 +100,8 @@ class BaseRenderer:

FALLBACK_THEME: str = ""

def __init__(self, directory: str, theme: str) -> None:
def __init__(self, directory: str, theme: str,
custom_templates: Optional[str] = None) -> None:
"""
Initialization method.
Expand All @@ -110,7 +111,13 @@ def __init__(self, directory: str, theme: str) -> None:
Arguments:
directory: The name of the directory containing the themes for this renderer.
theme: The name of theme to use.
custom_templates: Directory containing custom templates.
"""

custom_dir = None
if custom_templates is not None:
custom_dir = Path(custom_templates).joinpath(directory, theme)

themes_dir = Path(__file__).parent.parent / "templates" / directory
theme_dir = themes_dir / theme
if not theme_dir.exists():
Expand All @@ -123,7 +130,13 @@ def __init__(self, directory: str, theme: str) -> None:
else:
raise ThemeNotSupported(theme)

self.env = Environment(autoescape=True, loader=FileSystemLoader(str(theme_dir)))
dirs = [str(theme_dir)]

# If the custom directory exists, we need to prepend it to the list:
if custom_dir is not None and custom_dir.exists():
dirs = [(str(custom_dir))] + dirs

self.env = Environment(autoescape=True, loader=FileSystemLoader(dirs))
self.env.filters["highlight"] = do_highlight
self.env.filters["any"] = do_any

Expand Down Expand Up @@ -211,7 +224,8 @@ def __init__(self, collector: BaseCollector, renderer: BaseRenderer) -> None:
self.renderer = renderer


def get_handler(name: str, theme: str) -> BaseHandler:
def get_handler(name: str, theme: str,
custom_templates: Optional[str] = None) -> BaseHandler:
"""
Get a handler thanks to its name.
Expand All @@ -223,14 +237,15 @@ def get_handler(name: str, theme: str) -> BaseHandler:
Args:
name: The name of the handler. Really, it's the name of the Python module holding it.
theme: The name of the theme to use.
custom_templates: Directory containing custom templates.
Returns:
An instance of a subclass of [`BaseHandler`][mkdocstrings.handlers.BaseHandler],
as instantiated by the `get_handler` method of the handler's module.
"""
if name not in HANDLERS_CACHE:
module = importlib.import_module(f"mkdocstrings.handlers.{name}")
HANDLERS_CACHE[name] = module.get_handler(theme)
HANDLERS_CACHE[name] = module.get_handler(theme, custom_templates)
return HANDLERS_CACHE[name]


Expand Down
8 changes: 6 additions & 2 deletions src/mkdocstrings/handlers/python.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
from markdown import Markdown
from mkdocs.utils import log

from typing import Optional

from . import BaseCollector, BaseHandler, BaseRenderer, CollectionError, DataType


Expand Down Expand Up @@ -230,17 +232,19 @@ class PythonHandler(BaseHandler):
"""The Python handler class, nothing specific here."""


def get_handler(theme: str) -> PythonHandler:
def get_handler(theme: str, custom_templates: Optional[str] = None) -> PythonHandler:
"""
Simply return an instance of `PythonHandler`.
Arguments:
theme: The theme to use when rendering contents.
custom_templates: Directory containing custom templates.
Returns:
An instance of `PythonHandler`.
"""
return PythonHandler(collector=PythonCollector(), renderer=PythonRenderer("python", theme))
return PythonHandler(collector=PythonCollector(),
renderer=PythonRenderer("python", theme, custom_templates))


def rebuild_category_lists(obj: dict) -> None:
Expand Down
1 change: 1 addition & 0 deletions src/mkdocstrings/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ class MkdocstringsPlugin(BasePlugin):
("watch", MkType(list, default=[])), # type: ignore
("handlers", MkType(dict, default={})),
("default_handler", MkType(str, default="python")),
("custom_templates", MkType(str, default=None))
)
"""
The configuration options of `mkdocstrings`, written in `mkdocs.yml`.
Expand Down

0 comments on commit 7360021

Please sign in to comment.