Drupal is a content management system, and one of the key purposes of a CMS is to deliver content in a readable form. That could be through a feed or API in a headless context, but the most common implementation is for the CMS to produce HTML to be delivered to a web browser.
Render arrays are Drupal's core mechanism for producing this output. In this article, we'll dig into how render arrays work and give an introduction to how to use one.
Why render arrays?
HTML is just specially-formatted text, so producing output from a CMS means constructing a text string. PHP is pretty good at manipulating text, and we can easily concatenate fragments of text together to form an HTML document.
In days of yore, Drupal did just that to construct a page. Each function that produced a page element would build some HTML text and return that, and other functions would stitch those together and pump them out to the web browser. This works.
However, there are plenty of drawbacks to that approach. Text alone is hard to scan for security vulnerabilities. It's easy for text to contain malformed HTML, especially when joining together big nested lists of things. Text is hard to alter later if other parts of the system want to change something.
The render system is designed to attack these problems. Instead of creating HTML snippets, Drupal module functions create arrays of structured information, which are later processed by the theme and render systems to produce HTML at the last possible minute. Arrays are easy to inspect and manipulate, so things stay transparent as long as they can.
What does a render array look like?
As you might expect, a render array is a PHP associative array structure. Some keys are interpreted in predefined ways. For example, the key #markup tells Drupal to treat the value as HTML to be placed on the page. The simplest possible render array, then, is an array with just that key:
public function page() {
return [
'#markup' => '<p>The simplest <b>render array</b> possible.</p>',
];
}
This will produce a page with that paragraph on it: