MkAdmonition

github Show source on GitHub

Admonition info box.

Example: Types

Jinja

{{ "Different types." | MkAdmonition(typ="warning") }}

Python

MkAdmonition(None, typ='warning')

Warning

Different types.

:::{warning}

Different types.

:::
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>Different types.</p>
</div>
.. warning:: 
    Different types.
> [!WARNING]
> Different types.
MkAdmonition
╰── MkText('Different types.')

Example: Collapsible and expandable

Jinja

{{ "Admonitions can also be collapsible." | MkAdmonition(collapsible=True, title="Expand me!", expanded=True) }}

Python

MkAdmonition(None, title='Expand me!', collapsible=True, expanded=True)
Expand me!

Admonitions can also be collapsible.

:::{dropdown} Expand me!
:open:
:color: info

Admonitions can also be collapsible.

:::
<details class="sd-dropdown sd-bg-info" open>
<summary>Expand me!</summary>
<p>Admonitions can also be collapsible.</p>
</details>
.. info:: Expand me!
    Admonitions can also be collapsible.
<details open>
<summary>Expand me!</summary>

Admonitions can also be collapsible.

</details>
MkAdmonition
╰── MkText('Admonitions can also be collapsible.')

Example: Inlined

Jinja

{{ "Inlined" | MkAdmonition(inline="left") }}

Python

MkAdmonition(None, inline='left')

Note

Inlined

:::{note}

Inlined

:::
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Inlined</p>
</div>
.. info:: 
    Inlined
> [!NOTE]
> Inlined
MkAdmonition
╰── MkText('Inlined')

class MkAdmonition(mkcontainer.MkContainer)

Name

Children

Inherits

MkContainer
mknodes.basenodes.mkcontainer
A node containing other MkNodes.

graph TD
  178616935["mkadmonition.MkAdmonition"]
  835538629["mkcontainer.MkContainer"]
  1956333208["mkcontainer.MkContainerBase"]
  1359323199["mknode.MkNode"]
  2751680898["builtins.object"]
  835538629 --> 178616935
  1956333208 --> 835538629
  1359323199 --> 1956333208
  2751680898 --> 1359323199
/home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mkadmonition/metadata.toml
[metadata]
icon = "octicon:info-16"
name = "MkAdmonition"

[requirements.extension.admonition]

[requirements.extension."pymdownx.details"]

[requirements.extension."pymdownx.superfences"]

[examples.annotations]
title = "Annotations"
python = """
import mknodes as mk
node = mk.MkAdmonition("MkAdmonitions can carry annotations(1).")
node.annotations[1] = "Super handy!"
node
"""

[examples.types]
title = "Types"
jinja = """
{{ "Different types." | MkAdmonition(typ="warning") }}
"""

[examples.collapsible]
title = "Collapsible and expandable"
jinja = """
{{ "Admonitions can also be collapsible." | MkAdmonition(collapsible=True, title="Expand me!", expanded=True) }}
"""

[examples.inlined]
title = "Inlined"
jinja = """
{{ "Inlined" | MkAdmonition(inline="left") }}
"""

[output.markdown]
template = """
{% if node.title or node.get_items() %}
{{ node.title_line }}
{{ node.get_items() | join(node.block_separator) | indent(first=True) }}
{% endif %}
"""

[output.block]
template = """
{{ node.fence_boundary }} admonition {{ node.typ }}{{ node.title | add(" | ") }}
{{ node.get_items() | join }}
{{ node.fence_boundary }}
"""

[output.rst]
template = """
.. {{ node.typ }}:: {{ node.title or "" }}
{{ node.get_items() | join(node.block_separator) | indent(first=True) }}
"""
mknodes.basenodes.mkadmonition.MkAdmonition
 17class MkAdmonition(mkcontainer.MkContainer):
 18    """Admonition info box."""
 19
 20    ICON = "octicons/info-16"
 21    ATTR_LIST_SEPARATOR = "    "
 22    REQUIRED_EXTENSIONS = [
 23        resources.Extension("admonition"),
 24        resources.Extension("pymdownx.details"),
 25        resources.Extension("pymdownx.superfences"),
 26    ]
 27
 28    def __init__(
 29        self,
 30        content: str | list[mknode.MkNode] | mknode.MkNode,
 31        *,
 32        typ: datatypes.AdmonitionTypeStr | str = "info",
 33        title: str | None = None,
 34        collapsible: bool = False,
 35        expanded: bool = False,
 36        inline: Literal["left", "right"] | None = None,
 37        **kwargs: Any,
 38    ) -> None:
 39        """Constructor.
 40
 41        Args:
 42            content: Admonition content
 43            typ: Admonition type
 44            title: Optional Admonition title
 45            collapsible: Whether Admontion can get collapsed by user
 46            expanded: Initial state if collapsible is set
 47            inline: Whether admonition should rendered as inline block
 48            kwargs: Keyword arguments passed to parent
 49        """
 50        self.typ = typ
 51        self.title = title
 52        self.collapsible = collapsible
 53        self.inline = inline
 54        self.expanded = expanded
 55        super().__init__(content=content, **kwargs)
 56
 57    def attach_annotations(self, text: str) -> str:
 58        # we deal with attaching annotations ourselves.
 59        return text
 60
 61    @property
 62    def title_line(self) -> str:
 63        block_start = "???" if self.collapsible else "!!!"
 64        if self.collapsible and self.expanded:
 65            block_start += "+"
 66        if self.inline:
 67            inline_label = " inline" if self.inline == "left" else " inline end"
 68        else:
 69            inline_label = ""
 70        ann_marker = " annotate" if self.annotations else ""
 71        title = f' "{self.title}"' if self.title is not None else ""
 72        optional = ann_marker + inline_label
 73        return f"{block_start} {self.typ}{optional}{title}"
 74
 75    def get_content(self) -> resources.NodeContent:
 76        """Single-pass: get markdown with custom admonition formatting and resources."""
 77        items = self.get_items()
 78        if not items and not self.title:
 79            return resources.NodeContent(
 80                markdown="",
 81                resources=self._build_node_resources(),
 82            )
 83
 84        # Collect content from children
 85        renderer = rendering.current()
 86        child_contents = [renderer.render_child(item) for item in items]
 87        child_markdowns = [content.markdown for content in child_contents]
 88
 89        text = "\n".join(child_markdowns)
 90        indented = textwrap.indent(text, "    ")
 91        annotations = f"\n{self.annotations}\n" if self.annotations else ""
 92        md = f"{self.title_line}\n{indented}\n{annotations}"
 93
 94        # Aggregate resources
 95        aggregated = self._build_node_resources()
 96        for child_content in child_contents:
 97            aggregated.merge(child_content.resources)
 98
 99        return resources.NodeContent(markdown=md, resources=aggregated)
100
101    def to_md_unprocessed(self) -> str:
102        content = self.get_content()
103        return content.markdown
Page info
Code for this page
mknodes.manual.nodes_section.create_section_for_nodes
 93def create_section_for_nodes(
 94    nav: mk.MkNav,
 95    klasses: Sequence[type[mk.MkNode]],
 96) -> mk.MkTable:
 97    table = mk.MkTable(columns=["Node", "Docstrings", "Markdown extensions"])
 98    for kls in klasses:
 99        tpl = "classpage_custom.jinja"
100        page = mk.MkClassPage(kls, icon=kls.ICON, template_path=tpl, parent=nav, hide="toc")
101        nav += page
102        if kls.STATUS:
103            page.metadata.status = kls.STATUS
104        elif kls.JS_FILES:
105            page.metadata.status = "js"
106        elif kls.CSS:
107            page.metadata.status = "css"
108        page.created_by = create_section_for_nodes
109        link = mk.MkLink(page, kls.__name__, icon=kls.ICON)
110        extensions = ", ".join(f"`{i}`" for i in kls.REQUIRED_EXTENSIONS)
111        table.add_row((link, kls.__doc__, extensions))
112    return table
Resources
Resources(css=[],
          markdown_extensions={'admonition': {},
                               'pymdownx.details': {},
                               'pymdownx.highlight': {'anchor_linenums': True,
                                                      'line_spans': '__span',
                                                      'pygments_lang_class': True},
                               'pymdownx.superfences': {'custom_fences': [{'class': 'mermaid',
                                                                           'format': <function fence_code_format at 0x7ff77e88b060>,
                                                                           'name': 'mermaid'}]},
                               'pymdownx.tabbed': {},
                               'tables': {}},
          plugins=[Plugin('mkdocstrings')],
          js=[],
          assets=[],
          packages=[])
Metadata
created:
  source_filename: /home/runner/work/mknodes/mknodes/src/mknodes/manual/nodes_section.py
  source_function: create_section_for_nodes
  source_line_no: 93
hide:
- toc
icon: octicons/info-16
title: MkAdmonition