You are here

public function StringListClassFormatter::viewElements in Element Class Formatter 8

Builds a renderable array for a field value.

Parameters

\Drupal\Core\Field\FieldItemListInterface $items: The field values to be rendered.

string $langcode: The language that should be used to render the field.

Return value

array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

Overrides ElementListClassTrait::viewElements

File

src/Plugin/Field/FieldFormatter/StringListClassFormatter.php, line 28

Class

StringListClassFormatter
Formatter for displaying strings in an HTML list.

Namespace

Drupal\element_class_formatter\Plugin\Field\FieldFormatter

Code

public function viewElements(FieldItemListInterface $items, $langcode) {
  if ($items
    ->isEmpty()) {
    return [];
  }
  $elements = [];
  $attributes = new Attribute();
  $class = $this
    ->getSetting('class');
  if (!empty($class)) {
    $attributes
      ->addClass($class);
  }
  foreach ($items as $delta => $item) {
    $elements[$delta] = [
      '#type' => 'inline_template',
      '#template' => '{{ value|nl2br }}',
      '#context' => [
        'value' => $item->value,
      ],
    ];
  }
  return [
    [
      '#theme' => 'item_list',
      '#items' => $elements,
      '#list_type' => $this
        ->getSetting('list_type'),
      '#attributes' => $attributes
        ->toArray(),
    ],
  ];
}