MkTable

github Show source on GitHub

Class representing a formatted table.

Description

Data: a mapping column -> cells, a list of rows (the first one is the header unless columns are given) or a list of dicts (see MkBaseTable). | in cells gets escaped.

Example: Regular

Jinja

{{ {"Column A": ["A", "B", "C"], "Column B": ["C", "D", "E"]} | MkTable }}

Python

MkTable(data={'Column A': ['A', 'B', 'C'], 'Column B': ['C', 'D', 'E']})

Column A

Column B

A

C

B

D

C

E

| Column A | Column B |
| -------- | -------- |
| A        | C        |
| B        | D        |
| C        | E        |
<table>
<thead>
<tr>
<th>Column A</th>
<th>Column B</th>
</tr>
</thead>
<tbody>
<tr>
<td>A</td>
<td>C</td>
</tr>
<tr>
<td>B</td>
<td>D</td>
</tr>
<tr>
<td>C</td>
<td>E</td>
</tr>
</tbody>
</table>
MkTable
├── MkText('A')
├── MkText('B')
├── MkText('C')
├── MkText('C')
├── MkText('D')
╰── MkText('E')

Example: From rows (the first one is the header unless columns are given)

Jinja

{{ [["Name", "Value"], ["a|b", "1"], ["c", "2"]] | MkTable }}

Python

MkTable(data={'Name': ['a|b', 'c'], 'Value': ['1', '2']})

Name

Value

a|b

1

c

2

| Name | Value |
| ---- | ----- |
| a\|b | 1     |
| c    | 2     |
<table>
<thead>
<tr>
<th>Name</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>a|b</td>
<td>1</td>
</tr>
<tr>
<td>c</td>
<td>2</td>
</tr>
</tbody>
</table>
MkTable
├── MkText('a|b')
├── MkText('c')
├── MkText('1')
╰── MkText('2')

Example: From list of dicts

Jinja

{{ [{"col 1": "abc", "col 2": "cde"}, {"col 1": "fgh", "col 2": "ijk"}] | MkTable }}

Python

MkTable(data={'col 1': ['abc', 'fgh'], 'col 2': ['cde', 'ijk']})

col 1

col 2

abc

cde

fgh

ijk

| col 1 | col 2 |
| ----- | ----- |
| abc   | cde   |
| fgh   | ijk   |
<table>
<thead>
<tr>
<th>col 1</th>
<th>col 2</th>
</tr>
</thead>
<tbody>
<tr>
<td>abc</td>
<td>cde</td>
</tr>
<tr>
<td>fgh</td>
<td>ijk</td>
</tr>
</tbody>
</table>
MkTable
├── MkText('abc')
├── MkText('fgh')
├── MkText('cde')
╰── MkText('ijk')

class MkTable(mkbasetable.MkBaseTable)

Name

Children

Inherits

MkDependencyGroups
mknodes.templatenodes.mkdependencygroups
Node to display optional dependencies or dependency groups as a table.

    Name

    Children

    Inherits

    MkBaseTable
    mknodes.basenodes.mkbasetable
    Base Class for MkTables. Only deals with managing the data.

    graph TD
      1430734008["mktable.MkTable"]
      3678415322["mkbasetable.MkBaseTable"]
      835538629["mkcontainer.MkContainer"]
      1956333208["mkcontainer.MkContainerBase"]
      1359323199["mknode.MkNode"]
      2751680898["builtins.object"]
      3678415322 --> 1430734008
      835538629 --> 3678415322
      1956333208 --> 835538629
      1359323199 --> 1956333208
      2751680898 --> 1359323199
    
    /home/runner/work/mknodes/mknodes/src/mknodes/basenodes/mktable/metadata.toml
    [metadata]
    icon = "octicon:table-24"
    name = "MkTable"
    
    [requirements.extension.tables]
    
    [examples.regular]
    title = "Regular"
    jinja = """
    {{ {"Column A": ["A", "B", "C"], "Column B": ["C", "D", "E"]} | MkTable }}
    """
    
    [examples.rows]
    title = "From rows (the first one is the header unless `columns` are given)"
    jinja = """
    {{ [["Name", "Value"], ["a|b", "1"], ["c", "2"]] | MkTable }}
    """
    
    [examples.list_of_dicts]
    title = "From list of dicts"
    jinja = """
    {{ [{"col 1": "abc", "col 2": "cde"}, {"col 1": "fgh", "col 2": "ijk"}] | MkTable }}
    """
    
    # [output.markdown]
    # template = """
    # {% for k in table_data.keys() %}
    # {% endfor %}
    # {% for row in self.iter_rows() %}
    # {% endfor %}
    
    # """
    
    mknodes.basenodes.mktable.MkTable
    36class MkTable(mkbasetable.MkBaseTable):
    37    """Class representing a formatted table.
    38
    39    Data: a mapping column -> cells, a list of rows (the first one is the header unless
    40    `columns` are given) or a list of dicts (see `MkBaseTable`). `|` in cells gets escaped.
    41    """
    42
    43    REQUIRED_EXTENSIONS = [resources.Extension("tables")]
    44
    45    def to_md_unprocessed(self) -> str:
    46        table_data = self.data  # property
    47        if not any(table_data[k] for k in table_data):
    48            return ""
    49        in_code = rendering.current().name != "material"
    50        headers = [escape_cell(k, in_code_spans=in_code) for k in table_data]
    51        rows = [
    52            [escape_cell(str(cell), in_code_spans=in_code) for cell in row]
    53            for row in self.iter_rows()
    54        ]
    55        widths = [
    56            max(len(h), *(len(row[i]) for row in rows)) if rows else len(h)
    57            for i, h in enumerate(headers)
    58        ]
    59        formatters = [f"{{:<{width}}}" for width in widths]
    60        headers = [formatters[i].format(h) for i, h in enumerate(headers)]
    61        divider = [width * "-" for width in widths]
    62        data = [[formatters[i].format(c) for i, c in enumerate(row)] for row in rows]
    63        header_txt = "| " + " | ".join(headers) + " |"
    64        divider_text = "| " + " | ".join(divider) + " |"
    65        data_txt = ["| " + " | ".join(line) + " |" for line in data]
    66        return "\n".join([header_txt, divider_text, *data_txt]) + "\n"
    
    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/table-24
    title: MkTable