You are here

public static function TwigTweakExtension::viewFilter in Twig Tweak 3.1.x

Same name and namespace in other branches
  1. 3.x src/TwigTweakExtension.php \Drupal\twig_tweak\TwigTweakExtension::viewFilter()

Returns a render array for entity, field list or field item.

Parameters

object|null $object: The object to build a render array from.

string|array $view_mode: Can be either the name of a view mode, or an array of display settings.

string $langcode: (optional) For which language the entity should be rendered, defaults to the current content language.

bool $check_access: (optional) Indicates that access check for an entity is required.

Return value

array A render array to represent the object.

File

src/TwigTweakExtension.php, line 543

Class

TwigTweakExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public static function viewFilter(?object $object, $view_mode = 'default', string $langcode = NULL, bool $check_access = TRUE) : array {
  $build = [];
  if ($object instanceof FieldItemListInterface || $object instanceof FieldItemInterface) {
    $build = $object
      ->view($view_mode);

    /** @var \Drupal\Core\Entity\Plugin\DataType\EntityAdapter $parent */
    if ($parent = $object
      ->getParent()) {
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromObject($parent
        ->getEntity()))
        ->applyTo($build);
    }
  }
  elseif ($object instanceof EntityInterface) {
    $build = \Drupal::service('twig_tweak.entity_view_builder')
      ->build($object, $view_mode, $langcode, $check_access);
  }
  return $build;
}