Skip to content
Snippets Groups Projects

Výsledkovka pomocí mo.web.table

Closed Jiří Setnička requested to merge jirka/table into master
1 file
+ 5
6
Compare changes
  • Side-by-side
  • Inline
+ 30
14
@@ -4,7 +4,7 @@ from flask import Response, url_for
from html import escape
import io
from markupsafe import Markup
from typing import Sequence, Optional, Iterable, Union
from typing import Any, Dict, Sequence, Optional, Iterable, Union
import urllib.parse
import werkzeug.exceptions
@@ -36,7 +36,20 @@ class Cell:
return self.text
def to_html(self) -> str:
return escape(self.text)
return '<td>' + escape(self.text)
class Row:
"""Řádek tabulky, definuje klíče. Může definovat HTML atributy řádku."""
keys: Dict[str, Any]
html_attr: Dict[str, str]
def __init__(self, keys: Dict[str, Any], html_attr: Dict[str, str] = {}):
self.keys = keys
self.html_attr = html_attr
def get(self, key: str) -> Any:
return self.keys.get(key)
class CellLink(Cell):
@@ -49,7 +62,7 @@ class CellLink(Cell):
self.hint = hint
def to_html(self) -> str:
a = '<a href="' + escape(self.url) + '"'
a = '<td><a href="' + escape(self.url) + '"'
if self.hint:
a += ' title="' + escape(self.hint) + '"'
return a + '>' + escape(self.text) + '</a>'
@@ -67,7 +80,7 @@ class CellCheckbox(Cell):
self.checked = checked
def to_html(self) -> str:
ch = f'<input type="checkbox" name="{self.name}" value="{self.value}"'
ch = f'<td><input type="checkbox" name="{self.name}" value="{self.value}"'
if self.checked:
ch += ' checked'
return ch + '>'
@@ -75,18 +88,24 @@ class CellCheckbox(Cell):
class Table:
columns: Sequence[Column]
rows: Iterable[dict]
rows: Iterable[Row]
filename: str
show_downlink: bool
table_class: str
def __init__(self, columns: Sequence[Column], rows: Iterable[dict], filename: str, show_downlink: bool = True):
def __init__(
self, columns: Sequence[Column], rows: Iterable[Row],
filename: str, show_downlink: bool = True,
table_class: str = "data"
):
self.columns = columns
self.rows = rows
self.filename = filename
self.show_downlink = show_downlink
self.table_class = table_class
def to_html(self) -> str:
tab = ['<table class=data>', '<thead>', '<tr>']
tab = [f'<table class="{self.table_class}">', '<thead>', '<tr>']
for c in self.columns:
tab.append(f'\t<th>{c.title}')
@@ -94,17 +113,14 @@ class Table:
tab.append('<tbody>')
for r in self.rows:
if r.get('_html_tr'):
tab.append(r.get('_html_tr'))
else:
tab.append('<tr>')
r_attr = [f' {key}="{val}"' for (key, val) in r.html_attr.items()]
tab.append(f'<tr{"".join(r_attr)}>')
for c in self.columns:
val = r.get(c.key)
if isinstance(val, Cell):
vals = val.to_html()
tab.append(val.to_html())
else:
vals = escape(str(val))
tab.append(f'\t<td>{vals}')
tab.append(f'\t<td>{escape(str(val))}')
tab.append('</table>')
if self.show_downlink:
Loading