The Definitive Guide to Drupal 7

Using the Render API

What is a Render Array?

Many of the variables in template files are straightforward, but you’ll notice that some of the variables are printed along with a function called render(). Render arrays are structured arrays that contain nested data and other information needed by Drupal to turn them into HTML using Drupal’s Render API. Variables that are render arrays are generally easy to spot in template files because they are printed using a function called render().

In page.tpl.php, you’ll notice that all of the regions are printed using the render() function. Each region is an element (another array) nested inside the $page array. The code in Listing 16–13 is all that’s needed to render each region. Each render() call returns fully formatted HTML for all the contents of the render array.

Listing 16–13. Printing regions in page.tpl.php using the render() function
  1. <?php print render($page['sidebar_first']); ?>

In prior versions of Drupal, you would just include <?php print $sidebar_first; ?>, which contained a fully formatted HTML string ready for printing. This worked, of course, but it wasn't very flexible. Let’s face it; there are only so many things you can do with a big glob of HTML markup at that stage.

In Drupal 7, these variables are sent to templates as nicely structured arrays. Instead of a glob of HTML markup, you get an array containing all sorts of information about the content inside it, down to attributes of specific links deep inside of it. This makes it incredibly easy to target specific content of the arrays and make any sort of changes you want to it at the last possible minute before it's rendered in the first place.

To find out what’s inside this array, use the dpm() function provided with the Devel module to print it inside of page.tpl.php: <?php dpm($page['sidebar_first']); ?>. As you can see in Figure 16–4, there are two top-level render elements inside this array, the Search form block and the Navigation block, which are currently printing in the first sidebar.

Screenshot of sidebar_first region array using dpm()
Figure 16–4. Contents of the $page['sidebar_first'] render array printed from page.tpl.php using dpm()

You are reading content from two chapters on Theme Development from The Definitive Guide to Drupal 7, written by Jacine Luisi and published by Apress on July 19, 2011. All rights reserved.