Guide · The Great Explainer · started 7 November 2026
Great tables, for Nim
Tabelline is what Italian children call the times tables, the little tables learned by heart in primary school. It is also the name of a new Nim library for making display tables: tables meant to be read by people, with a title, grouped rows, labels over columns, formatted numbers, colours and notes. This page explains where the idea comes from (R's gt and Python's Great Tables), how those libraries are built, who uses them, and then builds a first, small tabelline, step by step.
Here is the first table every Italian pupil meets, la tavola pitagorica, made with tabelline from scratch. The code ran when this page was built.
First the data: a column × with the numbers 1 to 10, then one column for each factor.
collect, from Nim's std/sugar, turns a for loop into a list, one value per turn (the
closest Nim has to a list comprehension), and
inside tableData: a for loop adds a column per turn, named $j:
let tavola = tableData:
`×`: collect(for i in 1 .. 10: i)
for j in 1 .. 10:
$j: collect(for i in 1 .. 10: i * j)
Then the table: tabella takes the data, and each line under it adds a part or a style.
One more line, nbTable pitagora, puts the table in the page
(where a table goes explains it):
let pitagora = tabella(tavola, rownameCol = "×"):
tabHeader md("La *tavola pitagorica*"), "the times table, from 1 × 1 to 10 × 10"
tabStubhead "×"
dataColor everything(), palette = palette("quaderno"), domain = (1.0, 100.0)
tabStyle style.text(weight = "bold", color = "var(--primary-text)"), loc.stub(), loc.columnLabels()
tabSourceNote md("Every cell is `row × column`. The squares are on the diagonal.")
optCssTheme()
colsAlign alCenter
| La tavola pitagorica | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|
| the times table, from 1 × 1 to 10 × 10 | ||||||||||
| × | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
| 2 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
| 3 | 3 | 6 | 9 | 12 | 15 | 18 | 21 | 24 | 27 | 30 |
| 4 | 4 | 8 | 12 | 16 | 20 | 24 | 28 | 32 | 36 | 40 |
| 5 | 5 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 |
| 6 | 6 | 12 | 18 | 24 | 30 | 36 | 42 | 48 | 54 | 60 |
| 7 | 7 | 14 | 21 | 28 | 35 | 42 | 49 | 56 | 63 | 70 |
| 8 | 8 | 16 | 24 | 32 | 40 | 48 | 56 | 64 | 72 | 80 |
| 9 | 9 | 18 | 27 | 36 | 45 | 54 | 63 | 72 | 81 | 90 |
| 10 | 10 | 20 | 30 | 40 | 50 | 60 | 70 | 80 | 90 | 100 |
Every cell is row × column. The squares are on the diagonal. | ||||||||||
What is a great table?
A plot shows the shape of data; a table shows the values. Tables are older than plots by a few thousand years (Sumerian clay tablets already had rows, columns, subtotals and a footer), and in the middle of the twentieth century, typeset tables reached a peak: the US Census Bureau's Manual of Tabular Presentation (1949) named every part of a table and said how to use it. Then computers made tables easy to compute and hard to make beautiful: a dataframe printed at the console, or a spreadsheet.
gt (R) and Great Tables (Python) bring the midcentury table back, from code. Their authors call the problem the great table dilemma: analyse in code and show a poor table, or copy the numbers into a spreadsheet to make a good one, and lose reproducibility. Their answer is a grammar of tables: a small set of named parts, and verbs that add parts, format values and style cells, one step at a time.
gt, in R
gt is by Richard Iannone at RStudio (now Posit). Development started in
2018 and the first CRAN release (0.2) came out in 2020; today it is at version 1.4. It is big:
about 84,000 lines of R and 202 exported functions, among them 32 fmt_* formatters, 18 vec_fmt_*
versions of them for plain vectors, 17 cols_*, 14 opt_* and 13 tab_* verbs. It renders to
HTML, LaTeX, RTF and Word, and to images.
Great Tables, in Python
Great Tables is the Python port, by Rich Iannone and
Michael Chow at Posit, announced in January 2024. It follows gt closely, with Python names
(GT(df).tab_header(...)), works with Pandas and Polars dataframes, and adds Polars selectors for
columns. It is about 42,000 lines of Python, MIT licensed, and peer reviewed by pyOpenSci. Its
blog post The Design Philosophy of Great Tables
is the best short read on why tables matter.
The parts of a table
Both libraries describe a table as six parts. Here they are, each coloured on a tabelline table (the planets of the Solar System, which we will meet again below):
let parts = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
tabHeader "Table header: title", "and subtitle"
tabStubhead "stub head"
tabSpanner "spanner label", ["diameter", "mass"]
colsHide ["density", "gravity", "day_length", "orbital_period", "mean_temp", "rings"]
colsLabel {"mass": "column", "diameter": "labels", "distance": "…", "moons": "…"}
tabSourceNote "Table footer: source notes and footnotes"
tabStyle style.fill(partTints[0]), loc.title(), loc.subtitle()
tabStyle style.fill(partTints[1]), loc.columnLabels(), loc.spanners()
tabStyle style.fill(partTints[2]), loc.stubhead()
tabStyle style.fill(partTints[3]), loc.stub()
tabStyle style.fill(partTints[4]), loc.rowGroups()
tabStyle style.fill(partTints[5]), loc.body()
tabStyle style.fill(partTints[6]), loc.sourceNotes()
fmtNumber "mass", decimals = 2
fmtInteger "diameter"
| Table header: title | ||||
|---|---|---|---|---|
| and subtitle | ||||
| stub head | spanner label | … | … | |
| labels | column | |||
| Terrestrial | ||||
| Mercury | 4,879 | 0.33 | 57.9 | 0 |
| Venus | 12,104 | 4.87 | 108.2 | 0 |
| Earth | 12,756 | 5.97 | 149.6 | 1 |
| Mars | 6,792 | 0.64 | 228.0 | 2 |
| Gas giant | ||||
| Jupiter | 142,984 | 1,898.00 | 778.5 | 95 |
| Saturn | 120,536 | 568.00 | 1432.0 | 146 |
| Ice giant | ||||
| Uranus | 51,118 | 86.80 | 2867.0 | 28 |
| Neptune | 49,528 | 102.00 | 4515.0 | 16 |
| Table footer: source notes and footnotes | ||||
- table header: a title and a subtitle (菜の花 nanohana)
- column labels: one per column, with spanner labels over groups of columns (勿忘草 wasurenagusa)
- stub head: the top-left corner, a label for the stub (紅梅 kōbai)
- stub: the row labels (洒落柿 sharegaki)
- row groups: labels that split the rows (藤 fuji)
- table body: the cells, where the data lives (苗 nae)
- table footer: footnotes, marked in the table, and source notes (瓶覗 kamenozoki)
The colours are light tints of Japanese traditional colours, and the names in brackets are theirs, as Nippon Colors lists them (菜の花 nanohana is the yellow of rapeseed in flower): those of Haru, the palette of these pages, and of its neighbours. The same parts can be shown on the planets table of the home page.
What they offer
The verbs come in families, named by prefix. Here is the menu, as a table (made with tabelline, of course), with what the first version of tabelline already has:
type Verb = object
family, verbs, does, tabelline: string
let menu = @[
Verb(family: "Create", verbs: "gt(), gt_preview(), gt_group()", does: "a table from a dataframe", tabelline: "tabella(), tableData:, tabellaPreview()"),
Verb(family: "Parts", verbs: "tab_header, tab_spanner, tab_stubhead, tab_row_group, tab_footnote, tab_source_note", does: "add the parts of a table", tabelline: "all six"),
Verb(family: "Format", verbs: "fmt_number, fmt_percent, fmt_currency, fmt_date, fmt_scientific, fmt_roman, fmt_markdown, fmt_image, fmt_flag, fmt_units, fmt_nanoplot, … (32)", does: "turn values into text", tabelline: "31, and fmt() for your own"),
Verb(family: "Substitute", verbs: "sub_missing, sub_zero, sub_small_vals, sub_large_vals, sub_values", does: "replace some values", tabelline: "all five"),
Verb(family: "Columns", verbs: "cols_label, cols_align, cols_width, cols_hide, cols_move, cols_merge, cols_nanoplot, … (17)", does: "change columns", tabelline: "label, label rotate, units, align, align decimal, width, hide, unhide, move, reorder, merge (4), add, summary columns, nanoplot"),
Verb(family: "Rows", verbs: "summary_rows, grand_summary_rows, rows_add, row_group_order", does: "add or order rows", tabelline: "rowGroupOrder, rowOrder, summaryRows, grandSummaryRows, rowsAdd, rowsHide"),
Verb(family: "Style", verbs: "tab_style + cell_fill, cell_text, cell_borders, from_column; tab_style_body; data_color; text_transform", does: "style cells by location or by value", tabelline: "tabStyle (with fromColumn or a proc of the row), tabStyleBody, dataColor, textTransform"),
Verb(family: "Options", verbs: "tab_options (about 200 settings), opt_stylize, opt_row_striping, opt_all_caps, opt_interactive, …", does: "change the whole table", tabelline: "tabOptions (165), 14 opt*"),
Verb(family: "Output", verbs: "as_raw_html, gtsave (html, png, pdf, rtf, docx, tex), as_latex, as_rtf, as_word, extract_body, extract_cells, extract_summary", does: "render, or get the built table back", tabelline: "toHtml, toText, toMarkdown, save, extractBody, extractCells, extractSummary"),
]
let menuTable = tabella(menu, rownameCol = "family"):
tabHeader "The gt menu", "verb families of gt and Great Tables, and what tabelline has so far"
colsLabel {"verbs": "gt / Great Tables verbs", "does": "what for", "tabelline": "tabelline today"}
colsWidth {"verbs": "45%"}
tabStyle style.text(font = "ui-monospace, Menlo, monospace", size = "85%"), loc.body(cols = "verbs")
tabStyle style.text(color = "var(--success-text)", weight = "bold"), loc.body(cols = "tabelline")
optAllCaps()
| The gt menu | |||
|---|---|---|---|
| verb families of gt and Great Tables, and what tabelline has so far | |||
| gt / Great Tables verbs | what for | tabelline today | |
| Create | gt(), gt_preview(), gt_group() | a table from a dataframe | tabella(), tableData:, tabellaPreview() |
| Parts | tab_header, tab_spanner, tab_stubhead, tab_row_group, tab_footnote, tab_source_note | add the parts of a table | all six |
| Format | fmt_number, fmt_percent, fmt_currency, fmt_date, fmt_scientific, fmt_roman, fmt_markdown, fmt_image, fmt_flag, fmt_units, fmt_nanoplot, … (32) | turn values into text | 31, and fmt() for your own |
| Substitute | sub_missing, sub_zero, sub_small_vals, sub_large_vals, sub_values | replace some values | all five |
| Columns | cols_label, cols_align, cols_width, cols_hide, cols_move, cols_merge, cols_nanoplot, … (17) | change columns | label, label rotate, units, align, align decimal, width, hide, unhide, move, reorder, merge (4), add, summary columns, nanoplot |
| Rows | summary_rows, grand_summary_rows, rows_add, row_group_order | add or order rows | rowGroupOrder, rowOrder, summaryRows, grandSummaryRows, rowsAdd, rowsHide |
| Style | tab_style + cell_fill, cell_text, cell_borders, from_column; tab_style_body; data_color; text_transform | style cells by location or by value | tabStyle (with fromColumn or a proc of the row), tabStyleBody, dataColor, textTransform |
| Options | tab_options (about 200 settings), opt_stylize, opt_row_striping, opt_all_caps, opt_interactive, … | change the whole table | tabOptions (165), 14 opt* |
| Output | as_raw_html, gtsave (html, png, pdf, rtf, docx, tex), as_latex, as_rtf, as_word, extract_body, extract_cells, extract_summary | render, or get the built table back | toHtml, toText, toMarkdown, save, extractBody, extractCells, extractSummary |
Beyond the verbs, both libraries ship datasets made for showing off tables (exibble,
countrypops, gtcars, sp500, pizzaplace, towny, ...), locales for numbers and dates in
hundreds of languages, colour palettes, Font Awesome icons and flags, and nanoplots: tiny
line and bar charts drawn in SVG inside a cell.
How they work inside
Reading the sources of both (gt's R/ folder and Great Tables' great_tables/ package) shows
the same design. It is the design tabelline borrows.
Two layers: the data and the spec
A gt table is not a table yet: it is the data plus a description of how to show it. In R, gt()
returns a list of small data frames, one per concern (_data, _boxhead, _stub_df,
_row_groups, _heading, _spanners, _footnotes, _styles, _formats, _substitutions,
_summary, _options, _transforms, _locale, ...), each set up by its own dt_*_init() and
read and written through dt__get() and dt__set(). In Python the same pieces are the fields of a
frozen dataclass, GTData, and every method returns a copy made with _replace(...). The
boxhead is the list of columns with their label, alignment, width and role (data, stub, row
group, hidden).
Nothing is computed until the end
Verbs only record what was asked. fmt_number() stores a formatting function together with the
columns and rows it covers (FormatInfo in Python, one function per output context: html,
latex, rtf, default). tab_style() stores the styles with a resolved location (loc.body(),
loc.column_labels(), ...). When the table is printed, build_data() runs: it applies the formats
cell by cell (the last one wins), the substitutions, column merges and text transforms, puts the
rows in display order, and numbers the footnotes in reading order.
HTML with its own CSS
Then the HTML renderer writes each part as a component: the heading and column labels in
<thead> (spanners take one row per level, and labels without a spanner span those rows), the
row groups, stub and body in <tbody>, and the notes in a <tfoot>. The look comes from one
stylesheet template (gt_styles_default.scss) where every option is a variable: gt compiles it
with Sass, Great Tables fills the $variables with Python's string.Template. All the CSS is
prefixed with the table's id, so many tables on a page do not clash: that is why a gt table is a
<div id="..."> holding a <style> and a <table class="gt_table">. Cell styles are written
inline. Other outputs (LaTeX, RTF, Word) reuse the built data with their own renderers.
Dataframes, any kind
Great Tables does not depend on Pandas or Polars: _tbl_data.py puts a small set of operations
(column names, get a column, select rows, ...) behind singledispatch functions, with one version
per dataframe library, loaded only if that library is. gt does the same through R's generic
data frame verbs.
Who uses them
The Table Contest
Since 2020, RStudio and then Posit have run a Table Contest, the table cousin of their Shiny and plotting contests. Entries are single tables or tutorials, static or interactive, and the judges look at both utility and beauty. Since 2024 Python entries are in too.
let contest = tableData:
year: [2020, 2021, 2022, 2024, 2025]
winner: ["Niels van der Velden", "Vladislav Fridkin", "Karina Bartolome", "Melissa Van Bussel", "Martin Stavro"]
entry: ["Editable data tables in Shiny with a SQL database", "Satellites: a table of the satellites in orbit",
"The grammar of tables in Python (pandas) and R (gt)", "Today's Top Hits: a Spotify dashboard, with six tutorial videos",
"United's fleet with fleetR: tables in a map, a dashboard and a book"]
tools: ["DT, Shiny", "Shiny, reactable, gt", "gt, pandas", "Quarto", "R, fleetR"]
note: ["over 80 entries; runner-up: a gt table generator for clinical data", "categories: interactive HTML, Shiny, static",
"honourable mentions include a gt book and gtExtras tables", "first year open to Python; prizes for Great Tables and Polars",
"runner-up: pixel art drawn with gt"]
let contestTable = tabella(contest, rownameCol = "year"):
tabHeader "Grand prizes of the Table Contest", "RStudio (2020-2022), then Posit (2024-2025); there was no 2023 edition"
colsLabel {"winner": "grand prize", "entry": "the table", "tools": "made with", "note": "also"}
tabStyle style.text(weight = "bold"), loc.body(cols = "winner")
tabStyle style.text(size = "85%", color = "var(--muted)"), loc.body(cols = "note")
tabFootnote "The 2025 winners were announced on 10 November 2025.", loc.body(cols = "winner", rows = where(it.year == 2025))
tabSourceNote md("Posit blog, [2020](https://www.r-bloggers.com/2020/12/winners-of-the-2020-rstudio-table-contest/), [2021](https://www.r-bloggers.com/2021/12/winners-of-the-2021-table-contest/), [2022](https://posit.co/blog/winners-of-the-2022-table-contest/), [2024](https://posit.co/blog/2024-table-contest-winners/), [2025](https://posit.co/blog/2025-table-contest-winners/)")
optStylize(style = 1, color = "blue")
| Grand prizes of the Table Contest | ||||
|---|---|---|---|---|
| RStudio (2020-2022), then Posit (2024-2025); there was no 2023 edition | ||||
| grand prize | the table | made with | also | |
| 2020 | Niels van der Velden | Editable data tables in Shiny with a SQL database | DT, Shiny | over 80 entries; runner-up: a gt table generator for clinical data |
| 2021 | Vladislav Fridkin | Satellites: a table of the satellites in orbit | Shiny, reactable, gt | categories: interactive HTML, Shiny, static |
| 2022 | Karina Bartolome | The grammar of tables in Python (pandas) and R (gt) | gt, pandas | honourable mentions include a gt book and gtExtras tables |
| 2024 | Melissa Van Bussel | Today's Top Hits: a Spotify dashboard, with six tutorial videos | Quarto | first year open to Python; prizes for Great Tables and Polars |
| 2025 | Martin Stavro1 | United's fleet with fleetR: tables in a map, a dashboard and a book | R, fleetR | runner-up: pixel art drawn with gt |
| 1 The 2025 winners were announced on 10 November 2025. | ||||
| Posit blog, 2020, 2021, 2022, 2024, 2025 | ||||
The special prizes say even more about how people use these tables: the best gt table of 2024 summarised education in Córdoba; 2024's Great Tables prize showed transit patterns with nanoplots, and its Polars prize the Euro NCAP safety ratings; in 2025 a tutorial rebuilt 24 tables of the APA Publication Manual, and the pharma prize went to submission-ready clinical tables made with gt and gridify.
Stories beyond the contest
- Pharma and clinical trials. gt's static outputs (PDF, RTF, Word) are what regulators receive, and the pharma community built on it: gtsummary (Daniel Sjoberg) turns models and data into publication tables with one call, and Posit's post The many reasons that pharmas love gt lists demographic tables, responder tables with subgroups, protocol deviations and listings.
- An ecosystem of extensions. gtExtras (Tom Mock)
adds sparklines, bar charts and themes; reactable and
reactablefmtr cover interactive tables, and gt itself gained
opt_interactive(). - Books and teaching. Albert Rapp's book Creating beautiful tables in R with {gt}, and many contest tutorials, teach table design (alignment, fewer lines, grouping) as much as the API.
- Science. Great Tables has posts on tables for scientific publishing, on LaTeX output, on the open transit data of SEPTA, and on plots inside tables.
Wrap or write?
Could Nim just wrap one of them? Wrapping R or Python would mean shipping an interpreter with every Nim program, and the value of gt is not in a piece of code that is hard to write (there is no numerical kernel, as there is in Polars) but in its design and its use cases: the parts, the verbs, the formats and the hundreds of options, collected over eight years from real tables. A table library is mostly careful string building, which Nim does well, at compile time too.
So tabelline is written from scratch, in plain Nim, with no dependencies: the core uses only
the standard library, and nimib is needed only for the nbTable block
(where a table goes), as nanuq is only for a table from a nanuq data frame. It copies the design of
gt and Great Tables (the two layers, lazy building, the parts, scoped CSS) and their names, in
camelCase, so that their documentation and gallery can be read as tabelline's: tab_header
is tabHeader, fmt_number is fmtNumber, loc.body() and style.fill() are the same. Where
Nim offers something better, it uses it.
The data model in Nim
Values and data
The data is a set of named columns of Values. A Value is a Nim object variant, so a column
can hold a missing value next to numbers, and a renderer can tell an int from a float:
type
ValueKind* = enum vkNull, vkBool, vkInt, vkFloat, vkString
Value* = object
case kind*: ValueKind
of vkNull: discard
of vkBool: b*: bool
of vkInt: i*: int
of vkFloat: f*: float
of vkString: s*: string
Column* = object
name*: string
values*: seq[Value]
TableData* = ref object # read once, never changed: copying a table never copies it
columns*: seq[Column]
Data comes from Nim values with no ceremony: a seq of objects or named tuples (each field a
column, read with fieldPairs), a CSV text (types inferred), or the tableData: block, where
each value is converted on its own, so nil can stand for a missing number.
Data that needs work first (grouped, summarised, pivoted, as data in R and Python usually is
before gt sees it) comes from a data frame. tabelline makes tables, not data frames:
import tabelline/nanuq makes tabella(df) work for a DataFrame of
nanuq, Polars for Nim, copying each column as ints,
floats, bools or text, and Polars' nulls as missing values. It is the one module that needs
nanuq, so the core keeps needing only the standard library:
import nanuq, nanuq/datasets
import tabelline, tabelline/nanuq
let byIsland = penguins().groupBy("island").agg(len().alias("n"))
let t = tabella(byIsland):
tabHeader "Penguins by island"
The spec
A Tabella (Italian for table) holds the data and everything said about it: the boxhead,
title and subtitle, stub and groups, spanners, formats, substitutions, styles, footnotes, source
notes and options. It is a plain value. Every verb takes one and returns the new one, with sink
so that a chain moves it along instead of copying:
proc tabHeader*(t: sink Tabella, title: Text, subtitle: Text = toText("")): Tabella =
result = t
result.title = title
result.subtitle = subtitle
So the verbs chain, tabella(data).tabHeader("Title").fmtNumber("x"), like gt's pipe and
Great Tables' methods, and a table is never changed behind your back. These pages write the
same table as tabella(data): body, one verb per line, which the macro turns into that chain.
What is sink? A note on the parameter t: sink Tabella. It tells Nim that the proc takes
ownership of the table it is given. When the caller does not use that table again, as in a
chain, where each step's result goes straight into the next, Nim moves it instead of copying
it. When the caller does use it again, Nim makes a copy, so the code means the same either way:
sink only makes chains cheaper. You never write it when you use tabelline; it shows up only in
the signatures of the verbs. On this page it appears in this one signature.
Small types for small ideas
Textis plain text, Markdown (md("**bold**")) or HTML (html("<b>")); a converter turns astringinto plainText, so most calls just take strings.ColSelselects columns: a name, an array of names, or a rule (everything(),numeric(),startsWith("pop"),ofKind(vkBool),positions(0, -1),named(it.len == 4), ...), and rules join with+,-and&. It is resolved when the verb is called, so a typo fails at once, with the list of the columns there are.RowSelselects rows: indices ([0, 2],0..3,-1or^1for the last) or a predicate,where(it["type"] == "Gas giant").itis a Nim idiom: infilterIt,mapItand the other...Ittemplates ofstd/sequtils, the template names the current elementitfor the code you write.wheredoes the same: it turns the condition into a proc of one row, namedit.locandstyleare empty objects used as namespaces, soloc.body(cols = "mass")andstyle.fill("var(--warning-soft)") & style.text(weight = "bold")read exactly like Great Tables.TabOptionsuses Nim 2's default field values for its options.
Three macros, and only where they help
tabOptions(rowStriping = true, ...)sets options by name; a macro, because a proc with dozens of optional parameters would be worse, and a typo is still a compile error.tableData:writes data as columns, one line each, converting every value on its own (sonilcan be a missing number), withforloops for columns made by rule.tabella(data): bodyreads each line ofbodyas a verb applied to the table, so a table reads like a recipe, withforloops andifs allowed in between. The verbs stay plain procs: the macro only rewritesverb(args)intot = verb(t, args).
R or Python?
tabelline takes the names of its verbs from gt, which Great Tables shares (tab_header,
fmt_number, cols_label, ...), written in camelCase. Where the two disagree, it mostly
follows Great Tables, because a Python call with keyword arguments is closer to a Nim call than
R's tidy evaluation. A few choices follow neither:
type Choice = object
topic, gt, greatTables, tabelline, follows: string
let rOrPython = @[
Choice(topic: "make a table", gt: "gt(df, rowname_col = \"x\")", greatTables: "GT(df, rowname_col=\"x\")", tabelline: "tabella(df, rownameCol = \"x\")", follows: "both"),
Choice(topic: "chain verbs", gt: "the pipe |>", greatTables: "methods: .tab_header()", tabelline: "the dot (any proc), or a tabella(df): block", follows: "R's pipe, plus a block"),
Choice(topic: "locations", gt: "cells_body(columns, rows)", greatTables: "loc.body(columns, rows)", tabelline: "loc.body(cols, rows)", follows: "Python"),
Choice(topic: "styles", gt: "list(cell_fill(), cell_text())", greatTables: "[style.fill(), style.text()]", tabelline: "style.fill() & style.text()", follows: "Python, & for the list"),
Choice(topic: "row numbers", gt: "from 1", greatTables: "from 0", tabelline: "from 0", follows: "Python"),
Choice(topic: "rows by value", gt: "rows = mass > 1", greatTables: "pl.col(\"mass\") > 1", tabelline: "where(it[\"mass\"] > 1)", follows: "neither"),
Choice(topic: "column helpers", gt: "starts_with(), everything()", greatTables: "Polars selectors, lists", tabelline: "startsWith(), everything()", follows: "R"),
Choice(topic: "labels", gt: "cols_label(a = \"A\")", greatTables: "cols_label(a=\"A\") or a dict", tabelline: "colsLabel {\"a\": \"A\"}", follows: "Python's dict"),
Choice(topic: "options", gt: "tab_options(heading.title.font.size = ...)", greatTables: "tab_options(heading_title_font_size=...)", tabelline: "tabOptions(headingTitleFontSize = ...)", follows: "Python, in camelCase"),
Choice(topic: "formatters alone", gt: "vec_fmt_number()", greatTables: "vals.fmt_number()", tabelline: "formatNumber()", follows: "neither: plain procs"),
]
let rOrPythonTable = tabella(rOrPython, rownameCol = "topic"):
tabHeader "R or Python?", "the same call in gt, Great Tables and tabelline"
colsLabel {"gt": "gt (R)", "greatTables": "Great Tables (Python)", "follows": "tabelline follows"}
colsMoveToStart "follows"
tabStyle style.text(font = "ui-monospace, Menlo, monospace", size = "85%"),
loc.body(cols = ["gt", "greatTables", "tabelline"])
optAllCaps()
| R or Python? | ||||
|---|---|---|---|---|
| the same call in gt, Great Tables and tabelline | ||||
| tabelline follows | gt (R) | Great Tables (Python) | tabelline | |
| make a table | both | gt(df, rowname_col = "x") | GT(df, rowname_col="x") | tabella(df, rownameCol = "x") |
| chain verbs | R's pipe, plus a block | the pipe |> | methods: .tab_header() | the dot (any proc), or a tabella(df): block |
| locations | Python | cells_body(columns, rows) | loc.body(columns, rows) | loc.body(cols, rows) |
| styles | Python, & for the list | list(cell_fill(), cell_text()) | [style.fill(), style.text()] | style.fill() & style.text() |
| row numbers | Python | from 1 | from 0 | from 0 |
| rows by value | neither | rows = mass > 1 | pl.col("mass") > 1 | where(it["mass"] > 1) |
| column helpers | R | starts_with(), everything() | Polars selectors, lists | startsWith(), everything() |
| labels | Python's dict | cols_label(a = "A") | cols_label(a="A") or a dict | colsLabel {"a": "A"} |
| options | Python, in camelCase | tab_options(heading.title.font.size = ...) | tab_options(heading_title_font_size=...) | tabOptions(headingTitleFontSize = ...) |
| formatters alone | neither: plain procs | vec_fmt_number() | vals.fmt_number() | formatNumber() |
Where a table goes
A Tabella is a value: building it draws nothing. It becomes text, Markdown or HTML when you ask,
and none of that needs nimib. Here is a small one, as text and as Markdown:
let small3 = tabella(tavolaPitagorica(3), rownameCol = "×"):
tabHeader "Up to 3 × 3"
echo small3 # text, as `$` gives
echo small3.toMarkdown # Markdown
Up to 3 × 3 ┌───┬───┬───┬───┐ │ │ 1 │ 2 │ 3 │ ╞═══╪═══╪═══╪═══╡ │ 1 │ 1 │ 2 │ 3 │ │ 2 │ 2 │ 4 │ 6 │ │ 3 │ 3 │ 6 │ 9 │ └───┴───┴───┴───┘ **Up to 3 × 3** | | 1 | 2 | 3 | |:--|--:|--:|--:| | 1 | 1 | 2 | 3 | | 2 | 2 | 4 | 6 | | 3 | 3 | 6 | 9 |
For HTML, small3.toHtml gives the table as a string to put in a page of your own,
small3.toHtml(makePage = true) the same table in a whole standalone page, and
small3.save("tavola.html") writes that page to a file:
import tabelline
let small3 = tabella(tavolaPitagorica(3), rownameCol = "×"):
tabHeader "Up to 3 × 3"
small3.save("tavola.html")
A table's HTML and its style
small3.toHtml is a <div class="tabella"> holding the <table>, and in front of it a <style>
with tabellaCss: the rules of every table, the same for all of them. Each value in those rules
is a CSS variable named after its option, with the default as fallback, so a table sets on its
<div> only the options it changes:
<div id="tabella-1f2e" class="tabella" style="--tb-table-font-size: 14px">
<style> :where(.tabella):not(#_) .tb_table { font-size: var(--tb-table-font-size, 16px); ... } </style>
<table class="tb_table"> ... </table>
</div>
So a table looks the same on any page, unless you ask it to take the page's colours
(tables that follow the page). A page can also set an option for
all its tables at once: .tabella { --tb-table-font-size: 14px }. A table that takes the page's
theme (optCssTheme()) gets the class tb_css_theme instead of the theme's variables: one rule in
tabellaCss sets them for every such table.
A page with many tables needs the rules once. small3.toHtml(withStyle = false) leaves the
<style> out: write tabellaStyle (the <style> element) once, or save tabellaCss to a file
and link it from every page of a site, and then each table without it. nbTable does this by
itself: the first table of a page carries the rules, the others do not.
Every rule starts with :where(.tabella):not(#_): it picks every table and weighs as much as an
id, so a rule of the page's own stylesheet wins or loses against the table's as it would against
#id. Rules of one table only (optCss, the vertical lines) stay in a <style> of that table,
scoped to its id. Why, and the other ways we considered:
One stylesheet for every table.
In nimib
This page is a nimib notebook, and tabelline is made to
live in them. import tabelline/nimib, the one module of tabelline that imports nimib, adds one
block, nbTable t, which keeps the HTML of the table and its Markdown, so the same notebook renders
to an HTML page and to a Markdown README:
import nimib, tabelline, tabelline/nimib
nbInit # or nbInitMd, for a README.md
nbCode:
let t = tabella(planets()):
tabHeader "The planets"
nbTable t
nbSave
On this page, an nbTable line after the code puts each table in the page; it is usually left out
of the code shown. When the code need not be shown, nbTable takes the data and the body itself,
and the table needs no name:
nbTable planets(), rownameCol = "planet":
tabHeader "The planets"
A first table, step by step
The planets of the Solar System, from NASA's fact sheet, come with tabelline. Printed as they are, they are a dataframe:
let p = planets()
echo p.names
let first = tabella(p):
colsHide ["density", "gravity", "day_length", "orbital_period", "rings"]
echo first
@["planet", "type", "mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "moons", "rings"] ┌─────────┬─────────────┬────────┬──────────┬──────────┬───────────┬───────┐ │ planet │ type │ mass │ diameter │ distance │ mean_temp │ moons │ ╞═════════╪═════════════╪════════╪══════════╪══════════╪═══════════╪═══════╡ │ Mercury │ Terrestrial │ 0.33 │ 4879 │ 57.9 │ 167 │ 0 │ │ Venus │ Terrestrial │ 4.87 │ 12104 │ 108.2 │ 464 │ 0 │ │ Earth │ Terrestrial │ 5.97 │ 12756 │ 149.6 │ 15 │ 1 │ │ Mars │ Terrestrial │ 0.642 │ 6792 │ 228.0 │ -65 │ 2 │ │ Jupiter │ Gas giant │ 1898.0 │ 142984 │ 778.5 │ -110 │ 95 │ │ Saturn │ Gas giant │ 568.0 │ 120536 │ 1432.0 │ -140 │ 146 │ │ Uranus │ Ice giant │ 86.8 │ 51118 │ 2867.0 │ -195 │ 28 │ │ Neptune │ Ice giant │ 102.0 │ 49528 │ 4515.0 │ -200 │ 16 │ └─────────┴─────────────┴────────┴──────────┴──────────┴───────────┴───────┘
echo draws a text table. tabella(p): body makes a table of p and applies the verbs of
body, one per line. From here on, nbTable t shows the HTML after each step. Step 1: name the
planets as the stub, group them by type, and give the table a header.
var t = tabella(p, rownameCol = "planet", groupnameCol = "type"):
tabHeader md("The **planets** of the Solar System"), "from the smallest orbit to the largest"
tabStubhead "planet"
colsHide ["density", "gravity", "day_length", "rings"]
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | mass | diameter | distance | orbital_period | mean_temp | moons |
| Terrestrial | ||||||
| Mercury | 0.33 | 4879 | 57.9 | 88.0 | 167 | 0 |
| Venus | 4.87 | 12104 | 108.2 | 224.7 | 464 | 0 |
| Earth | 5.97 | 12756 | 149.6 | 365.2 | 15 | 1 |
| Mars | 0.642 | 6792 | 228.0 | 687.0 | -65 | 2 |
| Gas giant | ||||||
| Jupiter | 1898.0 | 142984 | 778.5 | 4331.0 | -110 | 95 |
| Saturn | 568.0 | 120536 | 1432.0 | 10747.0 | -140 | 146 |
| Ice giant | ||||||
| Uranus | 86.8 | 51118 | 2867.0 | 30589.0 | -195 | 28 |
| Neptune | 102.0 | 49528 | 4515.0 | 59800.0 | -200 | 16 |
Step 2: labels with units, and spanners to say what goes together. tabella(t): body adds
verbs to a table already made. A verb that takes pairs, as colsLabel, takes them as a block,
one per line:
t = tabella(t):
colsLabel:
mass: md("mass<br>10^24^ kg")
diameter: md("diameter<br>km")
distance: md("from the Sun<br>10^6^ km")
orbital_period: md("year<br>days")
mean_temp: md("mean<br>°C")
moons: md("moons")
tabSpanner "Size", ["mass", "diameter"]
tabSpanner "Orbit", ["distance", "orbital_period"]
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4879 | 57.9 | 88.0 | 167 | 0 |
| Venus | 4.87 | 12104 | 108.2 | 224.7 | 464 | 0 |
| Earth | 5.97 | 12756 | 149.6 | 365.2 | 15 | 1 |
| Mars | 0.642 | 6792 | 228.0 | 687.0 | -65 | 2 |
| Gas giant | ||||||
| Jupiter | 1898.0 | 142984 | 778.5 | 4331.0 | -110 | 95 |
| Saturn | 568.0 | 120536 | 1432.0 | 10747.0 | -140 | 146 |
| Ice giant | ||||||
| Uranus | 86.8 | 51118 | 2867.0 | 30589.0 | -195 | 28 |
| Neptune | 102.0 | 49528 | 4515.0 | 59800.0 | -200 | 16 |
Step 3: format the numbers, so that they line up and say only what matters.
t = tabella(t):
fmtNumber "mass", decimals = 3, dropTrailingZeros = true
fmtInteger ["diameter", "distance", "orbital_period"]
fmtNumber "mean_temp", decimals = 0, forceSign = true
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4,879 | 58 | 88 | +167 | 0 |
| Venus | 4.87 | 12,104 | 108 | 225 | +464 | 0 |
| Earth | 5.97 | 12,756 | 150 | 365 | +15 | 1 |
| Mars | 0.642 | 6,792 | 228 | 687 | −65 | 2 |
| Gas giant | ||||||
| Jupiter | 1,898 | 142,984 | 778 | 4,331 | −110 | 95 |
| Saturn | 568 | 120,536 | 1,432 | 10,747 | −140 | 146 |
| Ice giant | ||||||
| Uranus | 86.8 | 51,118 | 2,867 | 30,589 | −195 | 28 |
| Neptune | 102 | 49,528 | 4,515 | 59,800 | −200 | 16 |
Step 4: colour by value, style a row, and add the notes. A palette is a list of colours,
each a hex value, one of the 148 CSS colour names ("darkgreen", "rebeccapurple") or of R's
("sienna4", as gt takes them), or the name of one of tabelline's palettes, as "rdbu" here. The footnote marks are numbered in
reading order, wherever they were added.
t = tabella(t):
dataColor "mean_temp", palette = palette("rdbu"), domain = (-200.0, 200.0)
tabStyle style.fill("var(--warning-soft)") & style.text(weight = "bold"),
loc.stub(rows = where(it.planet == "Earth"))
tabFootnote "Known moons as of 2024; the counts keep growing.", loc.columnLabels("moons")
tabFootnote "Venus is hotter than Mercury: its thick atmosphere traps the heat.",
loc.body(cols = "mean_temp", rows = where(it.planet == "Venus"))
tabSourceNote md("Source: NASA, [Planetary Fact Sheet](https://nssdc.gsfc.nasa.gov/planetary/factsheet/).")
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons1 | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4,879 | 58 | 88 | +167 | 0 |
| Venus | 4.87 | 12,104 | 108 | 225 | +4642 | 0 |
| Earth | 5.97 | 12,756 | 150 | 365 | +15 | 1 |
| Mars | 0.642 | 6,792 | 228 | 687 | −65 | 2 |
| Gas giant | ||||||
| Jupiter | 1,898 | 142,984 | 778 | 4,331 | −110 | 95 |
| Saturn | 568 | 120,536 | 1,432 | 10,747 | −140 | 146 |
| Ice giant | ||||||
| Uranus | 86.8 | 51,118 | 2,867 | 30,589 | −195 | 28 |
| Neptune | 102 | 49,528 | 4,515 | 59,800 | −200 | 16 |
| 1 Known moons as of 2024; the counts keep growing. | ||||||
| 2 Venus is hotter than Mercury: its thick atmosphere traps the heat. | ||||||
| Source: NASA, Planetary Fact Sheet. | ||||||
Step 5: add it up. summaryRows adds rows under each group, one for each aggregate, and
grandSummaryRows rows for the whole table, set apart by a double rule. Each summary cell is
formatted like its column, so the masses keep their three decimals:
t = tabella(t):
summaryRows:
total: agg.sum
columns = ["mass", "moons"]
missingText = ""
grandSummaryRows:
"in all": agg.sum
largest: agg.max
columns = ["mass", "diameter", "moons"]
missingText = ""
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons1 | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4,879 | 58 | 88 | +167 | 0 |
| Venus | 4.87 | 12,104 | 108 | 225 | +4642 | 0 |
| Earth | 5.97 | 12,756 | 150 | 365 | +15 | 1 |
| Mars | 0.642 | 6,792 | 228 | 687 | −65 | 2 |
| total | 11.812 | 3 | ||||
| Gas giant | ||||||
| Jupiter | 1,898 | 142,984 | 778 | 4,331 | −110 | 95 |
| Saturn | 568 | 120,536 | 1,432 | 10,747 | −140 | 146 |
| total | 2,466 | 241 | ||||
| Ice giant | ||||||
| Uranus | 86.8 | 51,118 | 2,867 | 30,589 | −195 | 28 |
| Neptune | 102 | 49,528 | 4,515 | 59,800 | −200 | 16 |
| total | 188.8 | 44 | ||||
| in all | 2,666.612 | 400,697 | 288 | |||
| largest | 1,898 | 142,984 | 146 | |||
| 1 Known moons as of 2024; the counts keep growing. | ||||||
| 2 Venus is hotter than Mercury: its thick atmosphere traps the heat. | ||||||
| Source: NASA, Planetary Fact Sheet. | ||||||
Step 6: the same table with optCssTheme(), the preset of these pages: its colours are the page's
own, so it follows the look you pick at the top (Tables that follow the page
explains it). Next to it, optStylize:
nbTable t.optCssTheme()
let stylized = tabella(t):
optStylize style = 2, color = "gray"
tabOptions:
headingAlign = "left"
tableFontSize = "14px"
nbTable stylized
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons1 | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4,879 | 58 | 88 | +167 | 0 |
| Venus | 4.87 | 12,104 | 108 | 225 | +4642 | 0 |
| Earth | 5.97 | 12,756 | 150 | 365 | +15 | 1 |
| Mars | 0.642 | 6,792 | 228 | 687 | −65 | 2 |
| total | 11.812 | 3 | ||||
| Gas giant | ||||||
| Jupiter | 1,898 | 142,984 | 778 | 4,331 | −110 | 95 |
| Saturn | 568 | 120,536 | 1,432 | 10,747 | −140 | 146 |
| total | 2,466 | 241 | ||||
| Ice giant | ||||||
| Uranus | 86.8 | 51,118 | 2,867 | 30,589 | −195 | 28 |
| Neptune | 102 | 49,528 | 4,515 | 59,800 | −200 | 16 |
| total | 188.8 | 44 | ||||
| in all | 2,666.612 | 400,697 | 288 | |||
| largest | 1,898 | 142,984 | 146 | |||
| 1 Known moons as of 2024; the counts keep growing. | ||||||
| 2 Venus is hotter than Mercury: its thick atmosphere traps the heat. | ||||||
| Source: NASA, Planetary Fact Sheet. | ||||||
| The planets of the Solar System | ||||||
|---|---|---|---|---|---|---|
| from the smallest orbit to the largest | ||||||
| planet | Size | Orbit | mean °C | moons1 | ||
| mass 1024 kg | diameter km | from the Sun 106 km | year days | |||
| Terrestrial | ||||||
| Mercury | 0.33 | 4,879 | 58 | 88 | +167 | 0 |
| Venus | 4.87 | 12,104 | 108 | 225 | +4642 | 0 |
| Earth | 5.97 | 12,756 | 150 | 365 | +15 | 1 |
| Mars | 0.642 | 6,792 | 228 | 687 | −65 | 2 |
| total | 11.812 | 3 | ||||
| Gas giant | ||||||
| Jupiter | 1,898 | 142,984 | 778 | 4,331 | −110 | 95 |
| Saturn | 568 | 120,536 | 1,432 | 10,747 | −140 | 146 |
| total | 2,466 | 241 | ||||
| Ice giant | ||||||
| Uranus | 86.8 | 51,118 | 2,867 | 30,589 | −195 | 28 |
| Neptune | 102 | 49,528 | 4,515 | 59,800 | −200 | 16 |
| total | 188.8 | 44 | ||||
| in all | 2,666.612 | 400,697 | 288 | |||
| largest | 1,898 | 142,984 | 146 | |||
| 1 Known moons as of 2024; the counts keep growing. | ||||||
| 2 Venus is hotter than Mercury: its thick atmosphere traps the heat. | ||||||
| Source: NASA, Planetary Fact Sheet. | ||||||
The six steps, in one tabella(data): body, are a recipe of the whole table (shortened here):
let planetsTable = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
tabHeader md("The **planets** of the Solar System"), "from the smallest orbit to the largest"
colsHide ["density", "gravity", "day_length", "rings"]
tabSpanner "Size", ["mass", "diameter"]
fmtNumber "mass", decimals = 3, dropTrailingZeros = true
dataColor "mean_temp", palette = palette("rdbu"), domain = (-200.0, 200.0)
summaryRows fns = {"total": agg.sum}, columns = ["mass", "moons"], missingText = ""
optCssTheme()
A tour of the formats
gt's exibble is a tiny dataset with a column of each kind, made for showing formats. Here each
column gets its own:
let tour = tabella(exibble(), rownameCol = "row", groupnameCol = "group"):
tabHeader "Formats on exibble", "one column, one format; missing values shown as —"
fmtScientific "num", decimals = 2
fmtCurrency "currency", currency = "EUR"
fmtDate "date", dateStyle = "day_month_year"
fmtMarkdown "char"
subMissing everything(), missingText = "—"
colsHide ["fctr", "time", "datetime"]
| Formats on exibble | ||||
|---|---|---|---|---|
| one column, one format; missing values shown as — | ||||
| num | char | date | currency | |
| grp_a | ||||
| row_1 | 1.11 × 10−1 | apricot | 15 January 2015 | €49.95 |
| row_2 | 2.22 | banana | 15 February 2015 | €17.95 |
| row_3 | 3.33 × 101 | coconut | 15 March 2015 | €1.39 |
| row_4 | 4.44 × 102 | durian | 15 April 2015 | €65,100.00 |
| grp_b | ||||
| row_5 | 5.55 × 103 | — | 15 May 2015 | €1,325.81 |
| row_6 | — | fig | 15 June 2015 | €13.26 |
| row_7 | 7.77 × 105 | grapefruit | — | — |
| row_8 | 8.88 × 106 | honeydew | 15 August 2015 | €0.44 |
The formatters are plain functions too, for use anywhere (Great Tables calls them vals), and
they know every locale of Unicode CLDR (657 of them):
echo formatNumber(1234567.891)
echo formatNumber(1234567.891, decimals = 1, sepMark = ".", decMark = ",") # Italian
echo formatCompact(1234567.891)
echo formatScientific(5.97e24)
echo formatPercent(0.1234)
echo formatCurrency(-49.95, "EUR")
echo formatRoman(2026)
echo formatDate("2026-11-07", "wday_month_day_year")
echo formatDate("2026-11-07", "yMMMEd", "it"), " · ", formatDate("2026-11-07", "yMMMEd", "ja")
1,234,567.89 1.234.567,9 1.2M 5.97 × 10²⁴ 12.3% −€49.95 MMXXVI Saturday, November 7, 2026 sab 7 nov 2026 · 2026年11月7日(土)
A table can take a locale, so every format follows it: the marks of numbers, where a currency goes, the names of months and days, and the order of a date:
let italiano = tabella(exibble(), locale = "it"):
colsHide ["char", "fctr", "time", "datetime", "row", "group"]
fmtNumber "num", decimals = 2
fmtCurrency "currency", currency = "EUR"
fmtDate "date", dateStyle = "yMMMEd"
tabHeader "Numeri all'italiana"
nbTable italiano
| Numeri all'italiana | ||
|---|---|---|
| num | date | currency |
| 0,11 | gio 15 gen 2015 | 49,95 € |
| 2,22 | dom 15 feb 2015 | 17,95 € |
| 33,33 | dom 15 mar 2015 | 1,39 € |
| 444,40 | mer 15 apr 2015 | 65.100,00 € |
| 5.550,00 | ven 15 mag 2015 | 1.325,81 € |
| lun 15 giu 2015 | 13,26 € | |
| 777.000,00 | ||
| 8.880.000,00 | sab 15 ago 2015 | 0,44 € |
locale = "it" is read by each format: fmtCurrency writes the euro after the amount, as Italian does, and fmtDate takes gt's flexible style "yMMMEd" (year, short month, day, weekday) in the Italian order. The data is Unicode CLDR's, generated into a Nim module once and committed with the code.
Units, chemical formulas and fractions are written as text, in gt's notation, and shown with
superscripts and subscripts, in labels (between {{ and }}) and in cells:
let lab = tableData:
substance: ["water", "ethanol", "table salt"]
formula: ["H2O", "C2H5OH", "NaCl"]
density: [997.0, 789.0, 2160.0]
cups: [1.0, 0.75, 0.125]
origin: ["IT", "FR", "DE"]
let labTable = tabella(lab, rownameCol = "substance"):
fmtChem "formula"
fmtInteger "density"
colsLabel:
density: "density, {{kg m^-3}}"
fmtFraction "cups"
fmtCountry "origin"
optCssTheme()
nbTable labTable
| formula | density, kg m−3 | cups | origin | |
|---|---|---|---|---|
| water | H2O | 997 | 1 | Italy |
| ethanol | C2H5OH | 789 | 3/4 | France |
| table salt | NaCl | 2,160 | 1/8 | Germany |
Rows and columns of your own
A table can show more than its data: columns merged into one cell, columns and rows added, totals
across each row (summaryColumns) and down each column (grandSummaryRows), indented row labels
and numbers lined up on their decimal mark:
let medals = tableData:
country: ["Norway", "Germany", "Italy"]
gold: [16, 12, 7]
silver: [8, 10, 8]
bronze: [13, 5, 9]
first: [1924, 1928, 1936]
last: [2026, 2026, 2026]
let podium = tabella(medals, rownameCol = "country"):
colsMergeRange "first", "last"
colsLabel:
first: "medals since"
summaryColumns:
total: agg.sum
columns = ["gold", "silver", "bronze"]
grandSummaryRows:
all: agg.sum
columns = ["gold", "silver", "bronze", "total"]
optCssTheme()
nbTable podium
| gold | silver | bronze | medals since | total | |
|---|---|---|---|---|---|
| Norway | 16 | 8 | 13 | 1924–2026 | 37 |
| Germany | 12 | 10 | 5 | 1928–2026 | 27 |
| Italy | 7 | 8 | 9 | 1936–2026 | 24 |
| all | 35 | 26 | 27 | — | 88 |
Rows can be indented under the row above, hidden (they stay in the data, but are not shown nor added up) or added, and the numbers lined up on their decimal mark, whatever their decimals:
let budget = tableData:
item: ["Home", "rent", "bills", "Food", "groceries", "eating out", "old phone plan"]
euro: [1100.0, 950, 150, 520, 400.25, 119.75, 30]
let month = tabella(budget, rownameCol = "item"):
tabHeader "A month's budget"
tabStubIndent where($it.item in ["rent", "bills", "groceries", "eating out"]), 1
rowsHide where($it.item == "old phone plan")
rowsAdd [(item: "Total", euro: 1620.0)]
fmtNumber "euro", decimals = 2, dropTrailingZeros = true
colsAlignDecimal "euro"
optCssTheme()
nbTable month
| A month's budget | |
|---|---|
| euro | |
| Home | 1,100 |
| rent | 950 |
| bills | 150 |
| Food | 520 |
| groceries | 400.25 |
| eating out | 119.75 |
| Total | 1,620 |
tabStubIndent takes a level from 0 to 5 (or "increase", "decrease"). rowsAdd takes a table, or Nim objects or tuples with some of the columns; the others are missing. colsAlignDecimal pads each number on the right with figure spaces, as wide as a digit, so the marks fall in one column; it works in text output too.
The stub can be more than one column, the highest level first: a maker is written once over its
models. The groups can be a column of the stub too, instead of a row above each group. Here are
some of the cars of gt's gtcars, one of gt's datasets that tabelline ships:
let deluxe = tabella(gtcars(), rownameCol = ["mfr", "model"], groupnameCol = "ctry_origin",
rowGroupAsColumn = true):
rowsHide where($it.mfr notin ["Lamborghini", "Maserati", "Bentley", "Rolls-Royce", "Acura", "Nissan"])
colsHide ["year", "trim", "bdy_style", "hp", "hp_rpm", "trq", "trq_rpm", "mpg_c", "mpg_h",
"drivetrain", "trsmn"]
fmtCurrency "msrp", currency = "USD", decimals = 0
colsLabel:
msrp: "price"
optCssTheme()
nbTable deluxe
| price | |||
|---|---|---|---|
| Italy | Lamborghini | Aventador | $397,500 |
| Huracan | $237,250 | ||
| Gallardo | $191,900 | ||
| Maserati | Granturismo | $132,825 | |
| Quattroporte | $99,900 | ||
| Ghibli | $70,600 | ||
| Japan | Acura | NSX | $156,000 |
| Nissan | GT-R | $101,770 | |
| United Kingdom | Bentley | Continental GT | $198,500 |
| Rolls-Royce | Dawn | $335,000 | |
| Wraith | $304,350 | ||
rownameCol takes a list of columns; a value equal to the one above it, in the same group, spans its rows (in text it is left blank). rowGroupAsColumn = true is the same as tabOptions(rowGroupAsColumn = true); the stubRowGroup* options style that column. gtcars(), countrypops(), illness() and metro() come from gt, as Great Tables ships them.
Big tables, and tables as data
A long table can be previewed: its first and last rows, with a row that says which are left out. Styles can come from the data, from another column or from a test of each value; and the table, once built, can be read back:
let cities = tabellaPreview(citta(), topN = 4, bottomN = 1):
fmtInteger "population"
fmtDate "counted", dateStyle = "yMMM"
tabStyleBody style.text(weight = "bold"), columns = "state", values = ["ITA"], targets = "row"
optCssTheme()
nbTable cities
echo extractCells(cities, "city").join(", ")
| city | state | population | counted | |
|---|---|---|---|---|
| 1 | Berlin | GER | 3,913,644 | Dec 2025 |
| 2 | Madrid | ESP | 3,506,730 | Jan 2025 |
| 3 | Rome | ITA | 2,745,062 | Jan 2026 |
| 4 | Paris | FRA | 2,047,602 | Jan 2026 |
| 5..94 | ||||
| 95 | Augsburg | GER | 301,105 | Dec 2024 |
Berlin, Madrid, Rome, Paris, , Augsburg
tabellaPreview takes a body of verbs, as tabella does. tabStyleBody finds the cells whose value is "ITA" and styles their row; extractCells gives back what the reader sees, in order, as text.
A colour, or any value of a style, can be read from another column of the same row with
fromColumn, so the data says how each cell looks:
let rocky = tableData:
planet: ["Mercury", "Venus", "Earth", "Mars"]
moons: [0, 0, 1, 2]
tone: ["var(--neutral-2)", "var(--warning-soft)", "var(--success-soft)", "var(--primary-soft)"]
let tones = tabella(rocky, rownameCol = "planet"):
tabStyle style.fill(fromColumn("tone")), loc.body(cols = "moons")
colsHide "tone"
optCssTheme()
nbTable tones
| moons | |
|---|---|
| Mercury | 0 |
| Venus | 0 |
| Earth | 1 |
| Mars | 2 |
Pictures in cells
A cell can hold a picture: an icon (any of the 2,163 of Font Awesome Free, drawn from its name), an image (a file, inlined into the page), or a nanoplot, a plot as small as a word. A column of numbers becomes one bar per row, from a zero line they share; the temperatures of the planets go both ways:
let warm = tabella(planets(), rownameCol = "planet"):
colsAdd "kind", proc (r: Row): Value =
toValue(case r["type"].s
of "Terrestrial": "mountain"
of "Gas giant": "cloud"
else: "snowflake")
colsHide ["type", "mass", "diameter", "density", "gravity", "day_length", "distance", "orbital_period", "rings"]
fmtIcon "kind"
fmtNanoplot "mean_temp", plotType = "bar",
options = nanoplotOptions(dataBarFillColor = "var(--primary)", dataBarStrokeColor = "var(--primary)",
dataBarNegativeFillColor = "var(--secondary)", dataBarNegativeStrokeColor = "var(--secondary)")
colsLabel:
mean_temp: "mean temperature, °C"
optCssTheme()
nbTable warm
| mean temperature, °C | moons | kind | |
|---|---|---|---|
| Mercury | 0 | ||
| Venus | 0 | ||
| Earth | 1 | ||
| Mars | 2 | ||
| Jupiter | 95 | ||
| Saturn | 146 | ||
| Uranus | 28 | ||
| Neptune | 16 |
fmtIcon reads the names in the column and draws the icons as SVG, in the colour of the text. fmtNanoplot on a column of numbers draws one bar per row; nanoplotOptions gives its colours, here the page's own. Point at a bar, or tap it, to read its value. An image can go anywhere text goes, a title or a label: localImage(file) inlines a file, webImage(url) links one.
A cell can also hold many values, and then it is a line, bar or box plot. colsNanoplot makes
one from several columns: here each row of the times table, all on the same axis
(autoscale), with a dashed line at its mean.
let rowsOf = tabella(tavolaPitagorica(6), rownameCol = "×"):
colsNanoplot ["1", "2", "3", "4", "5", "6"], newColLabel = "the row", autoscale = true,
referenceLine = "mean",
options = nanoplotOptions(dataLineStrokeColor = "var(--primary)", dataPointFillColor = "var(--secondary)",
dataAreaFillColor = "var(--secondary)")
optCssTheme()
nbTable rowsOf
| the row | |
|---|---|
| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 |
colsNanoplot joins the six columns of each row into one cell, "1 2 3 4 5 6", hides them, and draws the new column with fmtNanoplot. The options for points and bars take a list too, one value for each point (dataPointFillColor = @["red", "blue"], repeating). echo rowsOf prints it as text, with a sparkline (▁▂▄▆█) in each row.
Nim sugar
Sugar is syntax that makes code sweeter to read and changes nothing of what it does. tabelline has a little of it, all on this page:
- the dot and the recipe,
tabella(data): body(pipes, methods and a recipe); - tables from any
seqof objects or tuples (tables from Nim values); tableData:, data written as columns (columns written as columns);forandifinside a recipe (loops inside a recipe);- verbs that take pairs, written as blocks (pairs as blocks);
- small words that read like Nim:
where(it["mass"] > 1),style.fill() & style.text(), astringwhere aTextis expected (small words); tabOptions(name = value), every option by name, checked when the program compiles.
Pipes, methods and a recipe
gt and Great Tables build a table one step at a time, each in the way of its language. R passes
the table along with the pipe, |>, which puts the value on its left as the first argument of
the call on its right. Python calls methods, functions that belong to the GT class: the dot in
.tab_header() works because GT defines tab_header. Nim has the dot too, and a third way
that a macro writes. The same table, in the three (the tabs switch the language):
let moonsData = tableData:
planet: ["Earth", "Mars", "Jupiter"]
moons: [1, 2, 95]
let dots = tabella(moonsData, rownameCol = "planet")
.tabHeader("Moons")
.colsLabel({"moons": "known moons"})
let recipe = tabella(moonsData, rownameCol = "planet"):
tabHeader "Moons"
colsLabel:
moons: "known moons"
echo $dots == $recipe
true
import polars as pl
from great_tables import GT
moons = pl.DataFrame({"planet": ["Earth", "Mars", "Jupiter"], "moons": [1, 2, 95]})
(
GT(moons, rowname_col="planet")
.tab_header("Moons")
.cols_label(moons="known moons")
)library(gt)
moons <- data.frame(planet = c("Earth", "Mars", "Jupiter"), moons = c(1, 2, 95))
moons |>
gt(rowname_col = "planet") |>
tab_header("Moons") |>
cols_label(moons = "known moons")| Moons | |
|---|---|
| known moons | |
| Earth | 1 |
| Mars | 2 |
| Jupiter | 95 |
- The dot is the pipe. In Nim,
t.tabHeader("Moons")is only another way to writetabHeader(t, "Moons"): the value before the dot is the first argument (method call syntax, or UFCS). So, as with R's pipe, every proc whose first parameter is aTabellachains, one of your own too, and no verb belongs to a class. In Python only what the class defines chains. - The recipe is a macro.
tabella(data): bodyis metaprogramming: the macro reads the lines ofbodywhile the program compiles and writes the chain,tabHeader "Moons"becomingt = tabHeader(t, "Moons"). Neither the pipe nor methods can do this: one verb per line, with no dots or parentheses,forandifin between, and the verbs that take pairs written as indented blocks. The two make the same table (thetrueabove); the pages of this site write the recipe. - R has metaprogramming too, of another kind: tidy evaluation lets
cols_label(moons = ...)name a column without quotes, because R can read the code of an argument before running it. Nim's happens when the program compiles, so a verb spelt wrong is an error before anything runs.
Tables from Nim values
Any seq of objects or named tuples is a table, one field per column:
type Pupil = object
name: string
tabellina: int
stars: int
passed: bool
let classe = @[Pupil(name: "Ada", tabellina: 7, stars: 3, passed: true),
Pupil(name: "Bruno", tabellina: 8, stars: 1, passed: false),
Pupil(name: "Carla", tabellina: 9, stars: 2, passed: true)]
let pupils = tabella(classe):
tabHeader "Who knows which tabellina"
fmt "stars", (v: Value) => "★".repeat(v.i)
fmtTf "passed", trueText = "bravo!", falseText = "ripassa"
echo pupils
Who knows which tabellina ┌───────┬───────────┬───────┬─────────┐ │ name │ tabellina │ stars │ passed │ ╞═══════╪═══════════╪═══════╪═════════╡ │ Ada │ 7 │ ★★★ │ bravo! │ │ Bruno │ 8 │ ★ │ ripassa │ │ Carla │ 9 │ ★★ │ bravo! │ └───────┴───────────┴───────┴─────────┘
fmt takes any proc from a Value to a string: here sugar's => makes stars.
Columns written as columns
The tableData: macro takes one line per column, and converts each value on its own, so a
missing value is just nil:
let d = tableData:
materia: ["matematica", "italiano", "scienze", "storia"]
voto: [9, 8, nil, 7]
let voti = tabella(d):
subMissing missingText = "assente"
echo voti
┌────────────┬─────────┐ │ materia │ voto │ ╞════════════╪═════════╡ │ matematica │ 9 │ │ italiano │ 8 │ │ scienze │ assente │ │ storia │ 7 │ └────────────┴─────────┘
Loops inside a recipe
Inside tabella(data): body, any for or if works, and their verbs are rewritten too. One
style per row of the times table, picking out the squares. The data is the one built at the top
of this page, ready made: tavolaPitagorica(n), from tabelline/datasets, is the n × n times table.
let squares = tabella(tavolaPitagorica(6), rownameCol = "×"):
tabHeader "Squares on the diagonal"
tabStubhead "×"
for i in 1 .. 6:
tabStyle style.fill("var(--warning-soft)") & style.text(weight = "bold"), loc.body(cols = $i, rows = [i - 1])
optCssTheme()
| Squares on the diagonal | ||||||
|---|---|---|---|---|---|---|
| × | 1 | 2 | 3 | 4 | 5 | 6 |
| 1 | 1 | 2 | 3 | 4 | 5 | 6 |
| 2 | 2 | 4 | 6 | 8 | 10 | 12 |
| 3 | 3 | 6 | 9 | 12 | 15 | 18 |
| 4 | 4 | 8 | 12 | 16 | 20 | 24 |
| 5 | 5 | 10 | 15 | 20 | 25 | 30 |
| 6 | 6 | 12 | 18 | 24 | 30 | 36 |
Columns and fields by name
In a row predicate, it is the row (the Nim idiom of filterIt, seen in
Small types for small ideas), and it.mass is its column
mass, the same as it["mass"]. A cell can also hold more than one value: a list (from a seq) or a
record (from an object or a named tuple), and v.name is a field of a record:
let sistema = tableData:
planet: ["Earth", "Mars", "Jupiter"]
moons: [@["Moon"], @["Phobos", "Deimos"], @["Io", "Europa", "Ganymede", "Callisto"]]
biggest: [(name: "Moon", km: 3474.8), (name: "Phobos", km: 22.5), (name: "Ganymede", km: 5268.2)]
let lune = tabella(sistema, rownameCol = "planet"):
rowsHide where(it.moons.len < 2)
fmtNumber "biggest", decimals = 0
echo lune
echo sistema["biggest", 2].name
┌─────────┬────────────────────────────────┬───────────────────────────┐ │ │ moons │ biggest │ ╞═════════╪════════════════════════════════╪═══════════════════════════╡ │ Mars │ Phobos, Deimos │ name: Phobos, km: 22 │ │ Jupiter │ Io, Europa, Ganymede, Callisto │ name: Ganymede, km: 5,268 │ └─────────┴────────────────────────────────┴───────────────────────────┘ Ganymede
The dot is a Nim dot operator: when a name is not a field or a proc of the value, it.mass becomes it["mass"]. So a name the value already has (kind, len, index) is that, and a Nim keyword (type) cannot follow a dot: write it["type"]. A misspelled name is found when the code runs, not when it compiles. A format works on each item of a list and each field of a record; icons, images, flags and nanoplots take a list whole.
Pairs as blocks
Some verbs take a list of pairs: a label and its value, as colsLabel, colsWidth,
colsUnits, textCaseMatch, summaryRows, grandSummaryRows and summaryColumns do. Inside
tabella(data): body, each of them also takes an indented block, one pair per line, so the
recipe reads as a list and not as punctuation:
let sums = tabella(planets(), rownameCol = "planet", groupnameCol = "type"):
colsHide ["density", "gravity", "day_length", "distance", "orbital_period", "mean_temp", "rings", "moons"]
colsLabel:
mass: "mass, {{10^24 kg}}"
diameter: "diameter, {{km}}"
fmtNumber:
columns = "mass"
decimals = 2
dropTrailingZeros = true
fmtInteger "diameter"
summaryRows:
total: agg.sum
columns = "mass"
missingText = ""
grandSummaryRows:
mean: agg.mean
"the largest": agg.max
fmtNumber(decimals = 0)
optCssTheme()
nbTable sums
| mass, 1024 kg | diameter, km | |
|---|---|---|
| Terrestrial | ||
| Mercury | 0.33 | 4,879 |
| Venus | 4.87 | 12,104 |
| Earth | 5.97 | 12,756 |
| Mars | 0.64 | 6,792 |
| total | 11.81 | |
| Gas giant | ||
| Jupiter | 1,898 | 142,984 |
| Saturn | 568 | 120,536 |
| total | 2,466 | |
| Ice giant | ||
| Uranus | 86.8 | 51,118 |
| Neptune | 102 | 49,528 |
| total | 188.8 | |
| mean | 333 | 50,087 |
| the largest | 1,898 | 142,984 |
Three kinds of line make a block. label: value is a pair, for the verbs above (a label with spaces is a string, "the largest", or in backquotes). name = value is a named argument, in any verb (columns = "mass"). In the summary verbs, fmtNumber(decimals = 0), or any fmt* that has a format* function, formats the summary rows: it stands for fmt = (x: float) => formatNumber(x, decimals = 0). tabOptions: takes name = value lines too. The pair form stays: summaryRows fns = {"total": agg.sum} makes the same call, and is the one to use outside tabella(data): body or when the pairs are built by code. For data, tableData: is the block form of toTableData.
Small words
A few names read like Nim, and are plain procs, templates and converters, not macros.
where(it["type"] == "Terrestrial") picks rows (a template: it is the row);
style.fill() & style.text() joins two styles, where Python writes a list and R list();
loc.body() and style.text() keep locations and styles in namespaces, as Great Tables does;
and converters turn a string into a Text, and a name or an array of names into a selection
of columns, where one is expected, so tabHeader "Moons" and colsUnhide ["moons"] need
nothing more.
let giants = tabella(planets(), rownameCol = "planet"):
colsHide everything()
colsUnhide ["moons"]
rowsHide where(it["type"] == "Terrestrial")
tabStyle style.fill("var(--warning-soft)") & style.text(weight = "bold"),
loc.body(rows = where(it["moons"].toFloat > 50))
optCssTheme()
| moons | |
|---|---|
| Jupiter | 95 |
| Saturn | 146 |
| Uranus | 28 |
| Neptune | 16 |
Tables that follow the page
Every table on these pages ends with optCssTheme(). It is the one verb here that gt and Great
Tables do not have.
One line
Here is a small table twice: on the left as it comes, on the right with optCssTheme() added.
Switch the look at the top of the page (Munari or quaderno): the right one changes with the page,
the left one stays as it is.
let moons = tableData:
planet: ["Mercury", "Earth", "Jupiter", "Saturn"]
kind: ["rocky", "rocky", "giant", "giant"]
moons: [0, 1, 95, 146]
let small = tabella(moons, rownameCol = "planet", groupnameCol = "kind"):
tabHeader "Moons"
| Moons | |
|---|---|
| moons | |
| rocky | |
| Mercury | 0 |
| Earth | 1 |
| giant | |
| Jupiter | 95 |
| Saturn | 146 |
| Moons | |
|---|---|
| moons | |
| rocky | |
| Mercury | 0 |
| Earth | 1 |
| giant | |
| Jupiter | 95 |
| Saturn | 146 |
A preset of colours that are not colours
In gt, every colour option takes any CSS colour: a name, #1C1C1C, and also var(--ink), a CSS
variable, whose value the browser looks up on the page when it draws the table. optCssTheme()
is a preset, like gt's opt_stylize(), but where opt_stylize() fills the options with fixed
colours, it fills them with the page's variables. In R you could write the same by hand, one
option at a time: tab_options(table.font.color = "var(--ink)", ...).
These are the variables it reads, here in the look you picked:
--ink, the inkthe text, the rules above and below, the rule under the column labels--paper, the paperbehind the table--line, a light greythe rules between rows--shade, a lighter greythe row groups, and the stripes when rows are striped--primary, the first colourthe rule under the headingand --font, the page's font.
Two are enough
Each variable comes with a fallback, written in the option itself. Without --ink and --paper
the table is black on white. Without --line and --shade, they are the ink mixed into the
paper, by the browser; without --primary, it is the ink. So a page that
sets only its ink and its paper already gets a whole table, and a page that sets nothing gets a
plain one, never a broken one:
let o = small.optCssTheme().options
echo o.tableFontColor
echo o.tableBodyHlinesColor
echo o.headingBorderBottomColor
var(--ink, #1C1C1C) var(--line, color-mix(in oklab, var(--ink, #1C1C1C) 14%, var(--paper, #FFFFFF))) var(--primary, var(--ink, #1C1C1C))
Other names, or values
Every name can be changed, in the call. An argument that starts with -- is the variable to
read; anything else is the colour itself, as in any gt option (primary = "red"). Here the rule
under the heading takes the page's green, and the rules between rows its soft blue:
nbTable small.optCssTheme(primary = "--success", line = "--secondary-soft")
| Moons | |
|---|---|
| moons | |
| rocky | |
| Mercury | 0 |
| Earth | 1 |
| giant | |
| Jupiter | 95 |
| Saturn | 146 |
A preset only fills options, so any option set after it still wins, for what the theme does not name, such as the width of the rules:
let ruled = tabella(small):
optCssTheme()
tabOptions:
tableBorderTopWidth = "1px"
tableBorderBottomWidth = "1px"
nbTable ruled
| Moons | |
|---|---|
| moons | |
| rocky | |
| Mercury | 0 |
| Earth | 1 |
| giant | |
| Jupiter | 95 |
| Saturn | 146 |
On your own page
Give the variables a value in your page's CSS, once, and every table made with optCssTheme()
takes it; change them, and every table changes. Two are enough:
:root { --ink: #102A43; --paper: #F0F4F8; }
If your theme already has its own names, there is no need to copy them: pass them. A theme to
keep, for every table of a site, is a CssTheme, made by cssTheme with the same arguments:
let site = cssTheme(ink = "--foreground", paper = "--background",
line = "--border", shade = "--muted")
let t = tabella(planets()):
optCssTheme site
nbTable t
How it is built
The preset is a proc that sets fourteen options, as opt_stylize() does in gt, and a small
object that says where each colour comes from. cssRef writes a variable with its fallback, or a
value as it is. This is the code, read from src/tabelline/verbs.nim when this page was built:
type CssTheme* = object
## Where a table takes its colours and font from (`optCssTheme`): for each, the name of a CSS
## variable of the page (`"--ink"`) or a CSS value (`"#1C1C1C"`).
ink*, paper*, line*, shade*, primary*, font*: string
func cssTheme*(ink = "--ink", paper = "--paper", line = "--line", shade = "--shade",
primary = "--primary", font = "--font"): CssTheme =
## A theme to keep and reuse with `optCssTheme(theme)`. Each argument starting with `--` names
## the variable to read; anything else is the CSS value itself.
CssTheme(ink: ink, paper: paper, line: line, shade: shade, primary: primary, font: font)
func cssRef(x, fallback: string): string =
## A variable with its fallback, or the value as it is.
if x.startsWith("--"): "var(" & x & ", " & fallback & ")" else: x
proc optCssTheme*(t: sink Tabella, theme: CssTheme): Tabella =
## Every colour of the table, and its font, from `theme`: see `optCssTheme()`.
let
ink = cssRef(theme.ink, "#1C1C1C")
paper = cssRef(theme.paper, "#FFFFFF")
line = cssRef(theme.line, "color-mix(in oklab, " & ink & " 14%, " & paper & ")")
shade = cssRef(theme.shade, "color-mix(in oklab, " & ink & " 4%, " & paper & ")")
result = t
result.options.tableFontNames = cssRef(theme.font, "system-ui, sans-serif")
result.options.tableFontColor = ink
result.options.tableBackgroundColor = paper
result.options.tableBorderTopColor = ink
result.options.tableBorderTopWidth = "3px"
result.options.tableBorderBottomColor = ink
result.options.tableBorderBottomWidth = "3px"
result.options.headingBorderBottomColor = cssRef(theme.primary, ink)
result.options.columnLabelsBorderBottomColor = ink
result.options.columnLabelsFontWeight = "bold"
result.options.tableBodyHlinesColor = line
result.options.rowGroupBackgroundColor = shade
result.options.rowGroupBorderColor = ink
result.options.rowStripingBackgroundColor = shade
result.options.summaryRowBorderColor = ink
result.options.summaryRowBorderWidth = "1px"
result.options.grandSummaryRowBorderColor = ink
result.options.grandSummaryRowBorderWidth = "4px"
proc optCssTheme*(t: sink Tabella, ink = "--ink", paper = "--paper", line = "--line",
shade = "--shade", primary = "--primary", font = "--font"): Tabella =
## The page's theme: every colour of the table, and its font, is a CSS variable of the page it
## is on, so the table follows the page's palette and changes with it. It reads `--ink` (text
## and the heavy rules), `--paper` (behind the table), `--line` (the rules between rows),
## `--shade` (row groups and stripes), `--primary` (the rule under the heading) and `--font`.
## Two are enough: without the others, line and shade are mixed from ink and paper, primary is
## the ink; without any, the table
## is black on white. An argument names another variable (`ink = "--foreground"`), or, when it
## does not start with `--`, is a value (`primary = "#D64545"`). gt and Great Tables have no
## such preset.
optCssTheme(t, cssTheme(ink, paper, line, shade, primary, font))
The table's CSS. Every table shares one stylesheet, tabellaCss, where each value is a
variable named after its option, and a table sets on its <div> the options it changes. So the
page's variables reach the browser untouched; these are the ones the table on the right above
sets:
for v in styleVars(small.optCssTheme().options).split("; "):
echo v
The page's variables. On these pages they are not written one by one. docs/theme.nim gives
each look six values (paper, ink, primary, secondary, warning, success), and mixes every other
colour from them in the browser: --neutral-0 (the paper) to --neutral-9 (the ink) are the
ink in the paper, step by step, --shade and --line are two of those steps, and --surface is
the paper with white. For Munari's palette, Haru:
for line in paletteCss(haru).splitLines:
if line.startsWith("--paper") or line.startsWith("--neutral-1:") or line.startsWith("--neutral-3:") or
line.startsWith("--shade:") or line.startsWith("--surface"):
echo line
--paper: #FCFAF2; --ink: #1C1C1C; --primary: #E16B8C; --secondary: #7DB9DE; --warning: #F7D94C; --success: #86C166; --neutral-1: color-mix(in oklab, var(--ink) 4%, var(--paper)); --neutral-3: color-mix(in oklab, var(--ink) 14%, var(--paper)); --shade: var(--neutral-1); --line: var(--neutral-3); --muted: var(--neutral-7); --surface: color-mix(in oklab, #FFFFFF 60%, var(--paper));
The switch. The look you pick sets data-tema on the page's <html>; the quaderno's six
values replace Munari's, the browser works out every variable again, and every table follows. The
tables were made once, when the page was built: nothing runs on them when the look changes.
What comes next
tabelline 0.1 had the basics of gt. 0.2, which this page shows,
adds summary rows and merges, every format and every locale, and pictures in cells. The roadmap has one more release after it. Each
release is tried on real subjects (the stories) and on ported reference code (the
book); the open steps are written down as specs (openspec/, on the
specs page) and in the backlog.
- 0.3, Out of the browser: LaTeX, RTF and Word, images and PDF of a table, groups of tables and split tables, and tables from more data frames (nanuq came with 0.2).
Some things are left aside for now, such as interactive tables: the roadmap says which, and why.
This page is a nimib notebook, docs/explainer.nim: every table on it was made by the code shown, when the page was built. The research behind it read the sources of gt and Great Tables and the Posit blog. Corrections are welcome, as issues or pull requests.