2

Behold, the code submitted by user Hecker:

(Quote) > writing html like a pro:
from typing import List
class MissmatchedRowsAndCols(Exception):
pass

class HtmlTableBuilder:
classes: List[str] = []
identifier: str = ""
rows: List[str] = []
cols: List[list] = []

def add_row(self, name: str):
self.rows.append(name)
return self

def add_col(self, fields: list):
if len(self.rows) != len(fields):
raise MissmatchedRowsAndCols(
"The given fields are not matched 1:1 with the rows.")
self.cols.append(fields)
return self

def build(self, indent: int = 4) -> str:
html = "<table border=\"2px\""
if len(self.identifier) > 0:
html += ' id="' + self.identifier + '"'
if len(self.classes) > 0:
html += ' class"' + (" ".join(self.classes)) + '"'
html += ">\n"

html += (" "*indent) + "<thead>\n"
for row in self.rows:
html += (" "*(indent*2)) + "<th>" + row + "</th>\n"
html += (" "*indent) + "</thead>\n"

html += (" "*indent) + "<tbody>\n"
for col in self.cols:
html += (" "*(indent*2)) + "<tr>\n"

for field in col:
html += (" "*(indent*3)) + "<td>\n"
html += (" "*(indent*4)) + str(field) + "\n"
html += (" "*(indent*3)) + "</td>\n"

html += (" "*(indent*2)) + "</tr>\n"
html += (" "*indent) + "</tbody>\n"
html += "</table>"

return html

builder = HtmlTableBuilder()
builder.add_row("index").add_row("language")
builder.add_col([0, "Python"]).add_col([1, "Kotlin"])

print(builder.build()) 

Comments
  • 0
    What actually is this
  • 0
    Yea thanks, I'll stick to Emmet.
  • 0
    Where's that bot that makes comments pretty?
  • 0
    Some caveman who hasn’t discovered jinja2
  • 2
    @tedge I tried to persuade him to use Jinja2
    He refused to use it.
    Because it brings thousands of code lines, while his solution takes just fifty code lines.
    And because it is not fun.
  • 0
    @darkwind at least he’s having fun playing code golf; be it at the expense of anyone who has to maintain this later.
Add Comment