Render Array Structure

A render array is, as it sounds, a hash array of configuration and data values.  In some cases, a data value can be another render array (normally done with the prebuilt theming template option), creating a nested arrangement that reflects the nesting of HTML tags in an HTML document.

There are three approaches to building up a single render array:

/* Render Array for a prebuilt theming template */

$render = [
  '#theme' => 'item_list',
  '#list_type' => 'ul',
  '#items' => ['item 1',  'item 2',  'item 3',
  ],
];

/* Render Array for preformatted HTML - Note that the HTML will be run through
 * a Cross Site Scripting (XSS) filter that strips form, form control, JavaScript and Style 
 * tags */

$render = [
  '#markup' => "<p>This is some <strong>regular old HTML markup.</p>",
];

/* Render Array for a common element type (most commonly used in form building
 * render arrays, and not all may work in a standard render array) */

$render = [
  '#type' => 'select',
  '#title' => $this->t('Select an Option'),   '#default_value' => $defaultValue,
  '#options' => array(1 => 'Yes', 0 => 'No'),
  '#required' => TRUE,
];

The examples above are generic ones that could be nested anywhere.  If one were used as the top-level array returned by module method directly to Drupal, then you may need some additional keys, including:

  '#attached' => [
    'library' => array('libraryID'),  
    /* List as array values all CSS/JavaScript libraries you want to included on the page */
  ],

  '#cache' => [
    /* Key/value pairs for caching configuration */
  ],

See Drupal's cacheability documentation for more details on configuring the caching of a render array structure.

Quick Tip: An easy way to group several render array objects to render one after the other is to place them inside a container object, which not only outputs all arrays specified as '#children', but also wraps the group in a DIV tag for easy formatting through CSS:

$render = [
  '#theme' => 'container',
  '#attributes' => [
    'class' => ['more-link'], /* Class on the wrapping DIV element */
  ],
  '#children' => [
    $render_array1,
    $render_array2,
    $render_array3,
  ],
];