Community Documentation

Render Arrays in Drupal 7

Last updated January 26, 2012. Created by rfay on October 4, 2010.
Edited by Spleshka, heather, soyarma, sven.lauer. Log in to edit this page.

"Render Arrays" or "Renderable Arrays" are the building blocks of a Drupal page, starting with Drupal 7. A render array is an associative array which conforms to the standards and data structures used in Drupal's theme rendering system.

In many cases, the data used to build a page (and all parts of it) is kept as structured arrays until the rendering stage in the theming system. This allows enormous flexibility in changing the layout or content of a page, and provides future performance enhancements as well.

What is "rendering"?

Rendering in the Drupal world means turning structured "render" arrays into HTML.

What is a render array?

A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type). A page array might look like this:

<?php
$page
= array(
 
'#show_messages' => TRUE,
 
'#theme' => 'page',
 
'#type' => 'page',
 
'content' => array(
   
'system_main' => array(...),
   
'another_block' => array(...),
   
'#sorted' => TRUE,
  ),
 
'sidebar_first' => array(
    ...
  ),
 
'footer' => array(
    ...
  ),
  ...
);
?>

Why was this done?

Before Drupal 7, we could alter things like forms (with hook_form_alter()), but so many other things that needed to be altered by a module or a theme had already been rendered into HTML before any rational thing could be done with them.

In Drupal 7 and later, a module or a theme can use hook_page_alter() to change the layout or content of the page at the very last moment. This means that a tidbit of PHP code in a theme can put that block over on the right side on one page when the customer needs it there.

Altering

Both blocks and pages can be altered just as forms have been alterable for some time. Many other types are also alterable. With hook_page_alter() both modules and themes can do things like this:

<?php
function mymodule_page_alter(&$page) {
 
// Move search form into the footer.
 
$page['footer']['search_form'] = $page['sidebar_first']['search_form'];
  unset(
$page['sidebar_first']['search_form']);
 
 
// Remove the "powered by Drupal" block
 
unset($page['footer']['system_powered-by']);
}
?>

How are Render Arrays Related to Elements?

Modules have the capability of defining "elements", which are essentially prepackaged default render arrays. They use hook_element_info() to do this. An element is essentially a prepackaged render array that has a #type and some other properties. When #type is declared for a render array, the default properties of the element type named are loaded through the use of hook_element_info().

Creating Content As Render Array

Unlike in past versions of Drupal, almost any time a module creates content, it should be in the form of a render array. A page callback should return a render array, as should hook_block_view()'s $block['content']. This allows your module and other modules to treat the content as data for as long as possible in the page generation process.

So a page callback might return this instead of the Drupal 6 method of rendering the data and gathering it as HTML:

<?php
function mymodule_menu() {
 
$items['mypage-html'] = array(
   
'title' => 'My page with HTML-style function',
   
'page callback' => 'mymodule_html_page',
   
'access callback' => TRUE,
  );

 
$items['mypage-ra'] = array(
   
'title' => 'My page with render array function',
   
'page callback' => 'mymodule_ra_page',
   
'access callback' => TRUE,
  );

  return
$items;
}

// Previous method (still works) of generating a page by returning HTML
function mymodule_html_page {
 
$output = '<p>A paragraph about some stuff...</p>';
 
$output .= '<ul><li>first item</li><li>second item</li><li>third item</li></ul>';
  return
$output;
}

// New method of generating the render array and returning that
function mymodule_ra_page {
 
$output =  array(
   
'first_para' => array(
     
'#type' => 'markup',
     
'#markup' => '<p>A paragraph about some stuff...</p>',
    ),
   
'second_para' => array(
     
'#items' => array('first item', 'second item', 'third item'),
     
'#theme' => 'item_list',
    ),
  );
  return
$output;
}
?>

Examples of Specific Array Types

As in the past, every Drupal "element" (see hook_element_info(), which was hook_elements() in Drupal 6) is a type. So anything that core exposes as an element or that an installed module exposes is available. Looking through system_element_info() we see a pile of predefined #types, including page, form, html_tag, value, markup, link, fieldset and many more. By convention, the #-properties used by these #types are documented with the respective theme function. So you can find out the properties used by #type => 'html_tag' elements by checking out the documentation for theme_html_tag(). You can also create types and properties on the fly. It's the Wild West out there.

Here are three examples pulled from the Examples Project's Render Example.

<?php
$demos
= array(
 
t('Super simple #markup')  => array(
   
'#markup' => t('Some basic text in a #markup (shows basic markup and how it is rendered)'),
  ),

 
'prefix_suffix' => array(
   
'#markup' => t('This one adds a prefix and suffix, which put a div around the item'),
   
'#prefix' => '<div><br/>(prefix)<br/>',
   
'#suffix' => '<br/>(suffix)</div>',
  ),

 
'theme for an element' => array(
   
'child' => array(
     
t('This is some text that should be put together'),
     
t('This is some more text that we need'),
    ),
   
'#separator' => ' | '// Made up for this theme function.
   
'#theme' => 'render_example_aggregate',
  ),
);
?>

A Sampling of Properties

Many, many properties can be applied in a given render array, and they can be created as needed. This will attempt to cover some of the most common.

Note that many of these properties are documented in the Form API Reference because the Form API has always used Render API properties, but they've traditionally not been documented as Render API properties, which they clearly are now in Drupal 7.

Property Description
#type The Element type. If this array is an element, this will cause the default element properties to be loaded, so in many ways this is shorthand for a set of predefined properties which will have been arranged through hook_element_info().
#markup The simplest property, this simply provides a markup string for #type => 'markup'
#prefix/#suffix A string to be prefixed or suffixed to the element being rendered
#pre_render An array of functions which may alter the actual render array before it is rendered. They can rearrange, remove parts, set #printed = TRUE to prevent further rendering, etc.
#post_render An array of functions which may operate on the rendered HTML after rendering. A #post_render function receives both the rendered HTML and the render array from which it was rendered, and can use those to change the rendered HTML (it could add to it, etc.). This is in many ways the same as #theme_wrappers except that the theming subsystem is not used.
#theme A theme hook (or array of theme hooks, but usually a singleton) which will take full responsibility for rendering this array element, including its children. It has predetermined knowledge of the structure of the element. Note: #theme in Drupal 7 and #theme in Drupal 6 are not really related. If you just stop thinking about Drupal 6 here, you will have an easier time.

Basically, the '#theme' = 'function_name' calls theme_function_name(), and other array values of the form '#var_name' = $value in the same array are passed as arguments to the theme function.

There is a list of all the default theme hooks at http://api.drupal.org/api/drupal/modules--system--theme.api.php/group/themeable/7

#theme_wrappers An array of theme hooks which will get the chance to add to the rendering after children have been rendered and placed into #children. This is typically used to add HTML wrappers around rendered children, and is commonly used when the children are being rendered recursively using their own theming information. It is rare to use it with #theme.
#cache Mark the array as cacheable and determine its expiration time, etc. Once the given render array has been rendered, it will not be rendered again until the cache expires. Caching uses standard Drupal cache_get() and cache_set() techniques. This is an array of
  • 'keys' => an array of keys which will be concatenated to form the cache key.
  • 'bin' => the name of the cache bin to be used (as in 'cache' or 'cache_page', etc.
  • 'expire' => a Unix timestamp indicating the expiration time of the cache.
  • 'granularity' => a bitmask indicating the cache type. This should be DRUPAL_CACHE_PER_PAGE, DRUPAL_CACHE_PER_ROLE, or DRUPAL_CACHE_PER_USER

Note that items marked with #cache will not be expired until cron runs, regardless of the expiration time used.

Since every element type can declare its own properties, there are many more. Many of these (often specific to a particular element type) are described on the Form API Reference handbook page.

Resources

Comments

Examples reorganised in git

Examples has been reorganised in git and source code link is now:

http://drupalcode.org/project/examples.git/blob/refs/heads/7.x-1.x:/rend...

(Now changed above)

Can we use

Can we use #attributes http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.... for any element? I try on a node field without success...

It should be mentioned that

It should be mentioned that render arrays for forms are different from other render arrays.
Render arrays for forms can only be created in modules (not in tpl.php files) and are not rendered with render().

render api reference

Is there a full reference, particularly for the #type property? A "sampling" as they offer above is not really adequate, nor is the Form API docs.

For example, I'm trying to put a table in my output array using this, and it isn't working:

$output['legend'] =  array(
            '#theme' => 'table',
            '#prefix' => '<div style="width: 250px"><h3>Legend</h3>',
            '#suffix' => '</div>',
            'content' => array('header' => $header, 'rows' => $legend)
          );

I get the prefix and suffix, but not the table. I'm assuming that I'm missing the #type, but can't for the life of me find what it should be.

It should be looked like

It should be looked like this:

$output['legend'] =  array(
                '#theme' => 'table',
                '#prefix' => '<div style="width: 250px"><h3>Legend</h3>',
                '#suffix' => '</div>',
                '#header' => $header,
                '#rows' => $rows, 
              );

Getting a render array for a node

To turn a node object into a render array use the node_view function:

<?php
function mymodule_callback($node) {
 
$node_render_array = node_view($node);
  return array(
   
'stuff' => array('#type' => 'markup', '#markup' => 'Here Is Some Stuff'),
   
'node' => $node_render_array,
   
'more_stuff' => array('#type' => 'markup', '#markup' => t('Here Is Some More Stuff')),
  );
}
?>

- - turpana.com - -

#type should be in quotes

In the section "Examples of Specific Array Types":
"...properties used by #type => 'html_tag' elements by checking..."

Should the above PHP code snippet be:
'#type' => 'html_tag'

Or am I wrong?

Valera Rozuvan | Валера Розуван

I think the #cache portion of

I think the #cache portion of this doc should be updated to include the fact that #pre_render is required to actually gain any benefit from using the #cache.

nobody click here