table.py (1082B) - raw
1 # -*- coding: utf-8 -*- 2 """ 3 Generate markdown tables programmatically. 4 """ 5 6 7 class Table: 8 matrix = {} 9 10 def __init__(self): 11 self.matrix = {} 12 13 def render_markdown(self): 14 """ 15 Render the table as markdown 16 """ 17 out = [] 18 headers = 0 19 for row_key, col in self.matrix.items(): 20 for cell_key, cell in col.items(): 21 if headers is not False: 22 headers += 1 23 out.append(f"| {cell} ") 24 25 out.append("|\n") 26 27 if headers is not False and headers > 0: 28 out.append("| :-- " * headers) 29 out.append("|\n") 30 headers = False 31 32 return "".join(out) 33 34 def add_data(self, row, cell, data): 35 if row not in self.matrix: 36 self.matrix[row] = {} 37 38 quoted = data.replace("\n", "<br>") 39 40 if cell in self.matrix[row]: 41 self.matrix[row][cell] += f"<br>{quoted}" 42 else: 43 self.matrix[row][cell] = quoted