5

I am dynamically rendering a table in a Drupal 8 module. While creating my renderable array I noticed that I can define my table as a '#theme' => 'table' or as '#type' => 'table'.

$variables['test_table'] = [
    '#theme' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

vs:

$variables['test_table'] = [
    '#type' => 'table',
    '#header' => $header,
    '#rows' => $rows,
    '#attributes' => array('class'=>array('my-table')),
    '#header_columns' => 4,
];

Both of these options seem to output the same thing.

My question is this: Why can I use either '#theme' => 'table' or '#type' => 'table' when defining a table renderable array and is there any difference between how Drupal will render these differently.

2 Answers 2

4

I believe ultimately both will do the same thing. But when you use 'type' you are referring to what drupal element to use (see https://api.drupal.org/api/drupal/elements) and when you use '#theme' you're directly telling it what twig template to use.

3

As Matt already said, the advantage of using #type is that you can have standard render array children instead of using #rows, which you shouldn't use with #type but works because it's basically just a wrapper that eventually uses `'#theme' => 'table' internally.

That allows to put form elements inside a table. In 7.x, this was always a pain that required custom theme functions to reshuffle a form structure back into something that the table template understands.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.