Matrix to Html Table

This page is about a particular problem. The problem is to turn a Julia matrix into the equivalent html table. To achieve this we have a table() function and two helper functions, row() and cell(). The output is a string with the original data from the supplied matrix inside all the necessary html tags.


# Output as a String, a table containing a sequence of rows.
function table(q)
    row(r) = "<tr>$(cell.(r) |> join)</tr>" # Output a row as a String of cells.
    cell(s) = "<td>$(string(s))</td>" # Output a single cell as a String.

    string("<table>",    
    ["$(row(data[n,:]))" for n in 1:size(q)[1]] |> join,
    "</table>")
end

# Usage: turn a matrix into a html table.
data = [1 2 3;
        4 5 6]
                
table(data)

The above produces the html as one long string. When the contents of this string are pasted into a html page the result is:

1 2 3
4 5 6

An interesting extension would be to have optional keyword arguments, for example, tableClass, rowClass and cellClass. When used they would pass class names into the table() function. The keywords would indicate where, in the table, tr or td elements, the classnames should be used. This would enable interesting, well-formatted tables to be created.

However, optional named parameters need a default value. Will an empty string be okay?


# Output as a String, a table containing a sequence of rows.
# The first, positional argument, is the matrix.
# Secondly we have a named argument.
function table(q; tableClass="", rowClass="", cellClass="")
    row(r) = "<tr class='$rowClass'>$(cell.(r) |> join)</tr>"
    cell(s) = "<td class='$cellClass'>$(string(s))</td>"

    string("<table class='$tableClass'>",    
    ["$(row(data[n,:]))" for n in 1:size(q)[1]] |> join,
    "</table>")
end

# Usage: turn a matrix into a html table.
data = [1 2 3;
        4 5 6]
                
table(data, tableClass="table_class", rowClass="row_class", cellClass="cell_class")

After adding a width manually, and defining the classes, the output is:

1 2 3
4 5 6

On testing what happens if a class name is not supplied, it seems that FireFox at least is okay with an empty string as a class name..