How to Replace Theme() Function in Drupal 8

How to Replace Theme() Function in Drupal 8

2 min read

Send to you:

Have you already worked with Drupal 8? If yes, this post could be useful for you. Sooner or later almost any web developer faces the surprise: theme() function is not included in Drupal 8. And those who is going to try a new Drupal 8 platform should be ready for changes. Today we’ll cope with this and find another effective and useful way.

Let me introduce a bit of history.

Theme () Function

Drupal 7 includes the theme() function. It is responsible for wrapping fields and the other outputting data in some HTML. theme() is pretty useful in many cases: it can theme the output of standard tables, menus, fields, breadcrumbs, etc.

But what to do without it in Drupal 8? Now I’m going to share one useful way of how to act in this case and replace theme() in Drupal 8. Here we go!

 Let’s Look at Drupal 7 Theme() Function

In Drupal 7, we can override all theme() functions at the level of your module.

The function could be overridden by adding another function with similar input parameters but the changed name (usually module name instead of theme_) into your module code.

A name of the theme (for example, ‘socbutt_buttons’) and an associative array of variables for transferring to hook_theme() are transferred into this function as parameters.

Here is how it works in Drupal 7:

echo theme('socbutt_buttons', array('layout' => SOCBUTT_LAYOUT_VERTICAL));
* Implements hook_theme().
function socbutt_theme() {
 return array(
   'socbutt_buttons' => array(
     'variables' => array(
       'layout' => SOCBUTT_LAYOUT_VERTICAL,
function theme_socbutt_buttons($variables) { 
	// Here is the code, which defines the look of things we want to display.

	// The array for displaying.
	return $output;

What About Drupal 8 Theme() Function?

The theme() function has been removed in Drupal 8. So you need to create a renderable array for theming required element. It is a data array which then is transmitted to the render() function.

Let’s do it in Drupal 8:

$items_array = array(
 '#theme' => 'theme_name',
 '#items' => $items;
echo Drupal::service('renderer')->render($items_array);

There you are! It’s an effective solution, which will help you to cope with your tasks without theme() and make the work with Drupal 8 more convenient.

Hope that this quick tip was useful for you and we’ll be glad to know your suggestions on this topic. Good luck to you! If you need any help, please contact us and we’ll do all these things on Drupal development.


Article rating (5 Reviews)

Do you find this article useful? Please, let us know your opinion and rate the post!

  • Not bad
  • Good
  • Very Good
  • Great
  • Awesome