function RenderExampleController::preRender

Same name in other branches
  1. 8.x-1.x render_example/src/Controller/RenderExampleController.php \Drupal\render_example\Controller\RenderExampleController::preRender()
  2. 4.0.x modules/render_example/src/Controller/RenderExampleController.php \Drupal\render_example\Controller\RenderExampleController::preRender()

A #pre_render callback, expand array to include additional example info.

This method is called during the process of rendering the array generated by \Drupal\render_example\Controller\RenderExampleController::arrays().

This also demonstrates how a #pre_render callback could be used to expand a relatively simple array into multiple individual renderable elements based on application logic.

Parameters

array $element: Pre render methods (and functions) get a single argument that is the render API array representing the element where the #pre_render property was defined, and all of it's children.

Return value

array Pre render methods (and functions) should return the modified render array.

File

modules/render_example/src/Controller/RenderExampleController.php, line 439

Class

RenderExampleController
Provides module description page and examples of building render arrays.

Namespace

Drupal\render_example\Controller

Code

public static function preRender(array $element) {
    // For each first level child element lets add some additional helpful
    // output. \Drupal\Core\Render\Element::children() is a utility method that
    // allows you to quickly identify all children of a render array. That is
    // those key/value pairs whose key does not start with a '#'.
    foreach (Element::children($element) as $key) {
        $child = $element[$key];
        unset($element[$key]);
        if (isset($child['#description'])) {
            $element[$key] = [
                // The value from the #description property will be used as a title
                // for this element in the final output.
'description' => [
                    '#markup' => $child['#description'],
                ],
                // Move the original element to 'rendered'. The rendering process is
                // recursive so this will still be located, and rendered to HTML.
'rendered' => $child,
                // Export the element definition as a string of text so we can display
                // the array that was used to create the rendered output just below
                // the output.
'unrendered' => [
                    '#markup' => htmlentities(Variable::export($child)),
                ],
                '#theme' => 'render_array',
            ];
        }
    }
    // Return our modified version of the original $element.
    return $element;
}