Tables

The last common theme hook we will look at now will help you build tables. It has always been a Drupal best practice to use the theme hook when building tables rather than creating the markup yourself. This is also, in part, because it has always been very flexible. So, let's take a look.

The table theme hook takes a bunch of variables, many of them optional. The most important, however, are the header (an array of header definitions) and rows (a multidimensional array of row definitions). It's not worth repeating all the possible options you have for building tables here because they are all very well documented above the template_preprocess_table() preprocessor function. So, do check there for more information. Instead, we'll focus on a simple use case of rendering a table, and we'll do so via an example:

$header = ['Column 1', 'Column 2'];
$rows = [
['Row 1, Column 1', 'Row 1, Column 2'],
['Row 2, Column 1', 'Row 2, Column 2']
];

return [
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
];

So, as you can see, we have the two critical variables. We have the list of header items and the rows (whose cells are in the array in the same order as the header). Of course, you have many more options, including attributes at all levels of the table, handy sorting capability that makes it easy to integrate with a database query, and more. I strongly encourage you to explore these options in the documentation.