You are here

public function TwigExtension::view in Twig Tweak 8.2

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

Parameters

mixed $object: The object to build a render array from.

string|array $display_options: 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/TwigExtension.php, line 1190

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function view($object, $display_options = 'default', $langcode = NULL, $check_access = TRUE) {
  if ($object instanceof FieldItemListInterface || $object instanceof FieldItemInterface) {
    return $object
      ->view($display_options);
  }
  elseif ($object instanceof EntityInterface) {
    $access = $check_access ? $object
      ->access('view', NULL, TRUE) : AccessResult::allowed();
    if ($access
      ->isAllowed()) {
      $build = \Drupal::entityTypeManager()
        ->getViewBuilder($object
        ->getEntityTypeId())
        ->view($object, $display_options, $langcode);
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromObject($object))
        ->merge(CacheableMetadata::createFromObject($access))
        ->applyTo($build);
      return $build;
    }
  }
}