Render Array Examples

<?php

/* To render formatted HTML directly.  Not recommended or preferred, but usable.
 * Note that this markup is run through Drupal's XSS filter which strips out most
 * form tags, script tags, and style tags among others. */

$render = [
  '#markup' => "<h2>My Sample HTML</h2><p>This is a sentence</p>",
];


/* To render formatted HTML using the 'full_html' text format.  Note that this is
 * not a very robust method to use, since across different sites you have no way
 * of knowing which text formats will be available or how they are configured. */

$render = [
  '#type' => 'processed_text',
  '#text' => '<p>Hello world</p>',
  '#format' => 'full_html',
];


/* To render an image (where $file contains a file entity) */

$render = [
  '#theme' => 'image',
  '#uri' => $file -> getFileUri(),
];


/* To render a responsive image (where $file contains a file entity and
 * 'your_responsive_style_id' matches a responsive style defined in this
 * instance of Drupal 8) */

$render = [
  '#theme' => 'responsive_image',
  '#responsive_image_style_id' => 'your_responsive_style_id',
  '#uri' => $file -> getFileUri(),
];


/* To render an ordered (ol) or unordered (ul) list */

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


/* To render a table (with an example of setting the 'class' attribute on
  * the table element.  This technique can be used on any element of a
  * table, and with elements rendered in most of the other themes
  * demonstrated on this page. */

$render = [
  '#theme' => 'table',
  '#caption' => 'My Table Caption',
  '#attributes' => array('class' => 'my-table-class'),
  '#header' => [
    '#attributes' => array('class' => 'my-header-class'),
    ['data' => 'Cell Value'], /* Cell */
    ['data' => 'Cell Value', '#attributes' => ['class' => 'text-align-right']], /* Cell aligned right */
    ['data' => 'Cell Value'], /* Cell */
  ],
  '#rows' => [
    'data' => [ /* Row */
      '#attributes' => ['class' => 'my-row-class'],
      [ 'data' => 'Cell Value'], /* Cell */
      [ 'data' => 'Cell Value', '#attributes' => ['class' => 'text-align-right']], /* Cell aligned right */
      [ 'data' => 'Cell Value'], /* Cell */
    ],
  ],
];


/* To render a group of children, put all of the child render arrays into a container */

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