Drupalwoo ☉

Build custom page output with Drupal's Render API

Drupal's Render API gives developers a structured way to assemble page output from reusable elements. Instead of returning a finished HTML string, a controller or service produces nested data that Drupal processes through its render pipeline. This makes the output easier to theme, cache, test and extend, particularly for dashboards, landing pages and administrative tools.

A useful custom page starts with a clear route, a predictable render array and a template that controls the final markup. The examples below use Drupal 10 and 11 conventions, although the same concepts apply to earlier supported versions. Keep user-supplied values out of raw markup, define access rules at the route, and decide which parts of the page can be cached before decorative refinements are added.

Start with a render array

A render array is a nested array in which each child describes one part of the output. The #type property selects a Drupal render element, while #theme selects a template hook. Additional properties control attributes, content, ordering and cache metadata. Child elements are usually rendered according to their weight.

$build = [
  '#type' => 'container',
  '#attributes' => ['class' => ['sales-dashboard']],
  'summary' => [
    '#theme' => 'item_list',
    '#items' => [
      ['data' => 'Sydney orders: 42'],
      ['data' => 'Melbourne orders: 37'],
    ],
  ],
];

This structure separates content from presentation. A module can obtain the values from a service, configuration or database query, then pass them into the render array without generating HTML. The #attributes property becomes part of the wrapper element, and the item list theme decides how each item is marked up.

Use #plain_text when the output is ordinary text. Reserve #markup for trusted or sanitised HTML, since it can bypass the escaping normally applied to text. Drupal also processes attachments, placeholders and cacheability information during the rendering pipeline, so the array remains the right boundary between business logic and presentation.

Connect a route to a controller

A route tells Drupal which controller should handle a URL and which permissions protect it. Keep the path and access requirement in the routing file rather than hiding them inside controller code. This makes the endpoint visible to site builders, automated tests and anyone reviewing the site's permissions.

custom.sales_dashboard:
  path: '/admin/reports/sales-dashboard'
  defaults:
    _controller: '\Drupal\custom\Controller\SalesDashboardController::page'
  requirements:
    _permission: 'view sales dashboard'

The controller can then assemble the render array and pass it to a template. ControllerBase::render() handles the HTTP response while the named template receives the variables required for the page.

public function page(): Response {
  $build = [
    '#type' => 'container',
    '#attributes' => ['class' => ['dashboard-content']],
  ];

  return $this->render('custom_sales_dashboard', [
    'title' => 'Sales dashboard',
    'build' => $build,
  ]);
}

A simple _permission requirement is suitable when everyone who reaches the route should see the same data. Use a custom access callback when access depends on the account, requested content or current configuration. Sensitive values should also be checked at the service layer, since a controller check alone does not protect data returned by an API or injected helper.

Build reusable render elements

A theme hook is often the simplest way to turn a render array into semantic markup. Define the template and its variables in the module's theme hook, then render it from the controller or another component. Drupal's Twig extension can render a render array passed as a variable.

function custom_theme() {
  return [
    'custom_sales_dashboard' => [
      'variables' => [
        'title' => NULL,
        'build' => NULL,
      ],
    ],
  ];
}
<div class="sales-dashboard">
  <h1>{{ title }}</h1>
  {{ build|render }}
</div>

The template should provide the document structure, while the render array supplies the data and Drupal-specific behaviour. Theme hooks work well for reusable cards, summaries and formatted lists. An element plugin is a stronger choice when a component needs its own JavaScript attachment, preparation logic, cache metadata or integration with other Drupal services.

Element plugins normally implement ElementInterface and extend ElementBase. They suit shared interface elements that several routes and modules consume. Keep the plugin focused on rendering rather than loading business data, and pass prepared values through its properties. This separation allows the same component to display a sales total in Brisbane, a stock level in Melbourne or a summary supplied by a Sydney-based operations team.

Control markup, caching, and accessibility

Render elements can carry their own attributes and attachments. Register JavaScript and CSS through the module's libraries.yml file, then attach those assets with #attached. Pass JavaScript settings as structured data rather than inserting scripts directly into markup.

$build['#attached']['library'][] = 'custom/sales-chart';
$build['#attached']['drupalSettings']['salesEndpoint'] = '/charts/sales';

$build['chart']['#attributes']['aria-label'] = 'Sales by region';

Accessibility depends on the final DOM, not merely on the existence of a render array. Use headings in a logical order, identify controls with labels, support keyboard operation and preserve visible focus. Australian project briefs often specify WCAG 2.2 AA, making these checks part of normal acceptance testing rather than an optional review. Consumer-facing Drupal sites should also provide clear contact information, privacy details and relevant complaint pathways, particularly where the Australian Consumer Law, Privacy Act 1988 or Spam Act 2003 applies.

Cache metadata should follow the sensitivity of the underlying data. Put account-specific output behind contexts such as user or user.permissions, add cache tags for source records and set a short max-age only when a brief delay is acceptable. Personalised dashboards often need a zero lifetime or explicit invalidation instead.

Timestamps deserve the same care. Drupal commonly stores dates in UTC, while a Brisbane office may need UTC+10 throughout the year and a Perth office may need UTC+8. Sydney and Melbourne observe daylight saving, so their displayed offsets change. Rendering an explicitly named Australian time zone prevents subtle reporting errors during transitions.

Add media and verify the result

Custom pages often combine operational data with supporting files or video. The Media Library checklist covers practical approaches to curating those assets before they are connected to a render array. Reference media entities rather than embedding unmanaged file paths, and expose the same access checks used by the media library.

When adding a download list, build each item from a media entity's URL, label and access status. Include file type and size where they help users make an informed choice. Images need suitable alternative text, while video requires captions or a transcript. These details remain important for Australian audiences and for organisations meeting WCAG 2.2 AA requirements.

Verification should cover more than a successful browser request. Render the array in a kernel test and assert the expected markup, then inspect its cacheability metadata. Test both anonymous and authorised accounts, confirm that denied users receive the intended response and check keyboard navigation. Placeholder-based and lazy-rendered elements also need testing, because an empty container in the initial response may be completed later by Drupal's rendering pipeline.

Different Drupal patterns suit different levels of reuse and complexity.

Approach Best fit Main strength Main limitation
Controller render array One custom route Direct and explicit control Logic can grow inside the controller
Theme hook Reusable visual component Simple templates and theming Limited built-in behaviour
Element plugin Shared interactive element Strong attachment and cache support Additional plugin setup
Entity view builder Node, term or media displays Native entity and access integration Less flexible for unrelated pages

For most bespoke internal pages, a controller-owned render array combined with a theme hook provides a clear balance between control and maintainability. It keeps data preparation in PHP, markup in Twig and Drupal's rendering services responsible for accessibility, caching and asset delivery.