In Drupal 7 I have a web site with dozens of custom templates. I used theme() to pass variables to my templates defined in hook_theme() in a page callback defined in hook_menu. How do you do this in Drupal 8? The theme() function is no longer available.

1 Answer 1


Drupal 8 uses render arrays for the structure, and drupal_render() to render them (as can Drupal 7 for themeing, incidentally).

The examples from the change record are as good as any:

Drupal 7

// Theme a table with header and row data.
$markup = theme('table', array('header' => $header, 'rows' => $rows, 'attributes' => array('id' => 'my-module-table')));

// Render a pager.
$markup = theme('pager');

Drupal 8

// Theme is available as an element type (may have additional processing in rendering).
$table = array(
  '#type' => 'table',
  '#header' => $header,
  '#rows' => $rows,
  '#attributes' => array(
    'id' => 'my-module-table',
$markup = drupal_render($table);

// Pager is not an element type, use #theme directly.
$pager = array('#theme' => 'pager');
$markup .= drupal_render($pager);

There's a useful warning too:

Also note that when preparing output for Twig templates (in preprocess functions) it is preferable to avoid calling drupal_render() whenever possible. The Twig environment in Drupal 8 will automatically render any render arrays printed in the template, allowing for manipulation by later preprocess functions and preventing unnecessary rendering if the variable is never printed in the template.

  • I think in the example \Drupal::service('renderer')->renderRoot() should be used instead of drupal_render() which is deprecated.
    – kenorb
    Aug 4, 2017 at 21:47

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.