1 | -- tabulate.lua |
2 | -- Formats input data with HTML table elements |
3 |
|
4 | -- Copyright (c) 2020 Joshua 'joshuas3' Stockin |
5 | -- <https://joshstock.in> |
6 |
|
7 | local html_format = function(str, element, class) |
8 | str = str or "" |
9 | element = element or "td" |
10 | local open = class == nil and "<"..element..">" or "<"..element.." class=\""..class.."\">" |
11 | local close = "</"..element..">" |
12 | return open..str..close |
13 | end |
14 |
|
15 | local _M = function(table_data) -- table to HTML |
16 | local table_string |
17 | local classes = {} |
18 |
|
19 | -- table HTML class? |
20 | if table_data.class then |
21 | table_string = "<table class=\""..table_data.class.."\">\n" |
22 | else |
23 | table_string = "<table>\n" |
24 | end |
25 |
|
26 | -- format th row |
27 | local header_row = "<tr>" |
28 | for _, header in pairs(table_data.headers) do |
29 | table.insert(classes, header[1]) -- populate classes data |
30 | local th = html_format(header[2], "th", header[1]) |
31 | header_row = header_row..th |
32 | end |
33 | header_row = header_row.."</tr>\n" |
34 | table_string = table_string..header_row |
35 |
|
36 | -- rows with td |
37 | for _, row in pairs(table_data.rows) do |
38 | local row_html = "<tr>" |
39 | for i, data in pairs(row) do |
40 | local class = classes[i] |
41 | local td = html_format(data, "td", class) |
42 | row_html = row_html..td |
43 | end |
44 | local row_html = row_html.."</tr>\n" |
45 | table_string = table_string..row_html |
46 | end |
47 |
|
48 | table_string = table_string.."</table>\n" |
49 |
|
50 | return table_string |
51 | end |
52 |
|
53 | return _M |
54 |
|