Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

64
LINES

< > BotCompany Repo | #1001986 // htmlTable (make HTML table from arbitrary data)

JavaX fragment (include)

// func(S) -> S
static new ThreadLocal htmlTable_cellEncoder;

// htmlEncode = true
static S htmlTable(O data) {
  ret htmlTable(data, true);
}

static S htmlTable(O data, boolean useHtmlEncode) {
  ret htmlTable(data, useHtmlEncode, false);
}

static S htmlTable(O data, boolean useHtmlEncode, boolean useBr) {
  // prepare table
  
  new L<L<S>> rows;
  new L<S> cols;
  
  if (data instanceof L) {
    for (O x : (L) data) pcall {
      rows.add(dataToTable_makeRow(x, cols));
    }
  } else if (data instanceof Map) {
    Map map = cast data;
    for (O key : map.keySet()) {
      O value = map.get(key);
      rows.add(litlist(structureOrText(key), structureOrText(value)));
    }
  } else
    print("Unknown data type: " + data);
    
  // get table width
  int w = 0;
  for (L<S> row : rows)
    w = max(w, l(row));
    
  // construct HTML for table
  
  new StringBuilder buf;
  buf.append("<table border>\n");
  
  // title
  buf.append("<tr>\n");
  for (S cell : padList(cols, w, "?"))
    buf.append("  <th>" + htmlTable_encodeCell(cell, useHtmlEncode, useBr) + "</th>\n");
  buf.append("</tr>\n");
  
  // data
  for (L<S> row : rows) {
    buf.append("<tr>\n");
    for (S cell : padList(row, w, ""))
      buf.append("  <td>" + htmlTable_encodeCell(cell, useHtmlEncode, useBr) + "</td>\n");
    buf.append("</tr>\n");
  }
  buf.append("</table>\n");
  ret buf.toString();
}

static S htmlTable_encodeCell(S cell, boolean useHtmlEncode, boolean useBr) {
  if (htmlTable_cellEncoder! != null) ret (S) callF(htmlTable_cellEncoder!, cell);
  if (useHtmlEncode) cell = htmlEncode(cell);
  if (useBr) cell = nlToBr(cell);
  ret cell;
}

Author comment

Began life as a copy of #1001613

download  show line numbers  debug dex  old transpilations   

Travelled to 13 computer(s): aoiabmzegqzx, bhatertpkbcr, cbybwowwnfue, cfunsshuasjs, gwrvuhgaqvyk, ishqpsrjomds, lpdgvwnxivlt, mqqgnosmbjvj, pyentgdyhuwx, pzhvpgtvlbxg, tslmcundralx, tvejysmllsmz, vouqrxazstgt

Comments [hide]

ID Author/Program Comment Date
1220 stefan htmlencode default = true
useBr default = false
2016-04-28 21:15:07

add comment

Snippet ID: #1001986
Snippet name: htmlTable (make HTML table from arbitrary data)
Eternal ID of this version: #1001986/4
Text MD5: 10bb32b74c0fe8d9c5e19ef04cfb66e1
Author: stefan
Category: javax html
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2019-02-24 12:23:09
Source code size: 1708 bytes / 64 lines
Pitched / IR pitched: No / No
Views / Downloads: 799 / 1189
Version history: 3 change(s)
Referenced in: [show references]