Skip to content

MkTable

Show source on GitHub

Class representing a formatted table.

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')

Bases: MkBaseTable

Name Children Inherits
MkBaseTable
mknodes.basenodes.mkbasetable
Base Class for MkTables. Only deals with managing the data.
graph TD
  94721306028880["mktable.MkTable"]
  94721311951440["mkbasetable.MkBaseTable"]
  94721311697232["mkcontainer.MkContainer"]
  94721308848336["mknode.MkNode"]
  94721311766592["node.Node"]
  140564252373184["builtins.object"]
  94721311951440 --> 94721306028880
  94721311697232 --> 94721311951440
  94721308848336 --> 94721311697232
  94721311766592 --> 94721308848336
  140564252373184 --> 94721311766592
/home/runner/work/mknodes/mknodes/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 }}
"""

[example.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
class MkTable(mkbasetable.MkBaseTable):
    """Class representing a formatted table."""

    REQUIRED_EXTENSIONS = [resources.Extension("tables")]

    def _to_markdown(self) -> str:
        table_data = self.data  # property
        if not any(table_data[k] for k in table_data):
            return ""
        widths = [self.width_for_column(c) for c in table_data]
        formatters = [f"{{:<{width}}}" for width in widths]
        headers = [formatters[i].format(k) for i, k in enumerate(table_data.keys())]
        divider = [width * "-" for width in widths]
        data = [
            [
                formatters[i].format(str(k).replace("\n", "<br>"))
                for i, k in enumerate(row)
            ]
            for row in self.iter_rows()
        ]
        header_txt = "| " + " | ".join(headers) + " |"
        divider_text = "| " + " | ".join(divider) + " |"
        data_txt = ["| " + " | ".join(line) + " |" for line in data]
        return "\n".join([header_txt, divider_text, *data_txt]) + "\n"