Change record status: 
Project: 
Introduced in branch: 
8.x
Introduced in version: 
8.0
Description: 

The direct callability of theme() was removed in favor of building render arrays consistently. It has been renamed to _theme() and is for internal use only. Build render arrays instead of using _theme() in your code for the following reasons.

Calling the _theme() function directly raises several issues:

  • It circumvents caching.
  • It circumvents defaults of types defined in hook_element_info(), including attached assets
  • It circumvents the pre_render and post_render stages.
  • It circumvents Javascript states information.

Theming should only be invoked as part of the drupal_render() process in order to convert data structures into output.

This issue has become clear as we have progressively hidden asset-adding functions like drupal_add_js() and drupal_add_css(). By making _theme() explicitly a private Drupal function, we reduced confusion for module developers.

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);

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.

Impacts: 
Module developers
Updates Done (doc team, etc.)
Online documentation: 
Not done
Theming guide: 
Not done
Module developer documentation: 
Not done
Examples project: 
Not done
Coder Review: 
Not done
Coder Upgrade: 
Not done
Other: 
Other updates done

Comments

rpayanm’s picture

Should be changed:

$markup .= drupal_render($pager);

instead of

$markup = drupal_render($pager);

while(alive){learn();}

kalinchernev’s picture