Render Array Structure
When to Use
Whenever you're building any render array -- understanding structure is foundational to using the Render API.
Structure Components
Render arrays have two types of keys:
| Key Type | Syntax | Purpose | Example |
|---|---|---|---|
| Properties | Start with # |
Control rendering behavior | #type, #theme, #markup, #cache, #access |
| Children | No # prefix |
Nested render arrays that become child content | 'title', 'body', 0, 1 |
Rendering order:
- Properties are processed to determine how to render
- Children are sorted by
#weight(if not#sorted = TRUE) - Children are rendered recursively
- Results are combined according to parent's
#themeor#type
Pattern: Nested Structure
$build = [
// Properties (start with #)
'#type' => 'container',
'#attributes' => ['class' => ['outer']],
'#weight' => 10,
'#cache' => ['contexts' => ['user']],
// Children (no # prefix)
'header' => [
'#type' => 'html_tag',
'#tag' => 'h2',
'#value' => $this->t('Title'),
'#weight' => -10, // Rendered first
],
'body' => [
'#markup' => $body_text,
'#weight' => 0,
],
];
Reference: core/lib/Drupal/Core/Render/RendererInterface.php (lines 93-99) -- properties vs children explanation
Common Mistakes
- Using
#prefix on child keys -- Makes them properties, not children -- they won't render - Forgetting
#sorted = TRUEwhen children are pre-sorted -- Wastes CPU on unnecessary sorting - Deeply nesting without considering cache contexts -- Cache contexts bubble up; every level needs appropriate metadata
- Mixing numeric and string child keys without understanding sort order -- Numeric keys sort before string keys; use
#weightfor explicit control
See Also
- Render Properties for property reference
- Cache Metadata in Render Arrays for metadata bubbling
- Reference: Render arrays documentation