You are here

public function TwigExtension::drupalEntity in Twig Tweak 8

Same name and namespace in other branches
  1. 8.2 src/TwigExtension.php \Drupal\twig_tweak\TwigExtension::drupalEntity()

Returns the render array for an entity.

Parameters

string $entity_type: The entity type.

mixed $id: The ID of the entity to render.

string $view_mode: (optional) The view mode that should be used to render the entity.

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

Return value

null|array A render array for the entity or NULL if the entity does not exist.

File

src/TwigExtension.php, line 162

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalEntity($entity_type, $id = NULL, $view_mode = NULL, $langcode = NULL) {
  $entity_type_manager = \Drupal::entityTypeManager();
  $entity = $id ? $entity_type_manager
    ->getStorage($entity_type)
    ->load($id) : \Drupal::routeMatch()
    ->getParameter($entity_type);
  if ($entity) {
    $access = $this
      ->entityAccess($entity);
    if ($access
      ->isAllowed()) {
      $build = $entity_type_manager
        ->getViewBuilder($entity_type)
        ->view($entity, $view_mode, $langcode);
      CacheableMetadata::createFromRenderArray($build)
        ->merge(CacheableMetadata::createFromObject($entity))
        ->merge(CacheableMetadata::createFromObject($access))
        ->applyTo($build);
      return $build;
    }
  }
}