Skip to content

Markdown

Markdown

Source code in dvc_render/markdown.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Markdown:
    RENDERERS_PLACEHOLDER = "renderers"
    RENDERERS_PLACEHOLDER_FORMAT_STR = f"{{{RENDERERS_PLACEHOLDER}}}"

    def __init__(
        self,
        template: Optional[str] = None,
    ):
        template = template or PAGE_MARKDOWN
        if self.RENDERERS_PLACEHOLDER_FORMAT_STR not in template:
            raise MissingPlaceholderError(
                self.RENDERERS_PLACEHOLDER_FORMAT_STR, "Markdown"
            )

        self.template = template
        self.elements: list[str] = []

    def with_element(self, md: str) -> "Markdown":
        "Adds custom markdown element."
        self.elements.append(md)
        return self

    def embed(self) -> str:
        "Format Markdown template with all elements."
        kwargs = {
            self.RENDERERS_PLACEHOLDER: "\n".join(self.elements),
        }
        for placeholder, value in kwargs.items():
            self.template = self.template.replace("{" + placeholder + "}", value)
        return self.template

embed()

Format Markdown template with all elements.

Source code in dvc_render/markdown.py
37
38
39
40
41
42
43
44
def embed(self) -> str:
    "Format Markdown template with all elements."
    kwargs = {
        self.RENDERERS_PLACEHOLDER: "\n".join(self.elements),
    }
    for placeholder, value in kwargs.items():
        self.template = self.template.replace("{" + placeholder + "}", value)
    return self.template

with_element(md)

Adds custom markdown element.

Source code in dvc_render/markdown.py
32
33
34
35
def with_element(self, md: str) -> "Markdown":
    "Adds custom markdown element."
    self.elements.append(md)
    return self

render_markdown(renderers, output_file=None, template_path=None)

User renderers to fill an Markdown template and write to path.

Source code in dvc_render/markdown.py
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def render_markdown(
    renderers: list["Renderer"],
    output_file: Optional["StrPath"] = None,
    template_path: Optional["StrPath"] = None,
) -> "StrPath":
    "User renderers to fill an Markdown template and write to path."
    output_path = None
    if output_file:
        output_path = Path(output_file)
        output_path.parent.mkdir(exist_ok=True)

    page = None
    if template_path:
        with open(template_path, encoding="utf-8") as fobj:
            page = fobj.read()

    document = Markdown(page)

    for renderer in renderers:
        document.with_element(renderer.generate_markdown(report_path=output_path))

    if output_file and output_path:
        output_path.write_text(document.embed(), encoding="utf8")

        return output_file

    return document.embed()