Module Development

Use a Component in a Module via Render Arrays for Drupal 10, 11

As a module developer, you output themed content from your module in the form of renderable arrays. When doing so, you can make use of single directory components (SDCs) by using the #type => 'component' render element type. This allows modules to dynamically select and configure a component based on configuration or specific PHP logic. You'll use this as the return value of a controller, or a configurable plugin related to display building, like custom blocks or field formatters. As an example, we'll author a custom block plugin that loads a specific node and outputs it using the card SDC we defined in a previous tutorial. We'll build a render array that supplies the values for the component's props and slots, and add some caching logic to the output.

In this tutorial, we will:

  • Build a render array that targets an SDC via the #component property.
  • Pass data into the component's props and slots, and demonstrate optional #propsAlter and #slotsAlter callbacks.
  • Validate the output and cache it properly.

By the end of this tutorial, you'll be able to render any SDC via a module's PHP code using a well-structured and cache-friendly render array.

Frontend Theming