You are here

public function TwigExtension::drupalEntity in Twig Tweak 8.2

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

Returns the render array to represent and entity.

Parameters

string $entity_type: The entity type.

mixed $id: (optional) The ID of the entity to build.

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.

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

Return value

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

File

src/TwigExtension.php, line 582

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, $check_access = TRUE) {
  $entity_type_manager = \Drupal::entityTypeManager();
  if ($id) {
    $entity = $entity_type_manager
      ->getStorage($entity_type)
      ->load($id);
  }
  else {
    @trigger_error('Loading entities from route is deprecated in Twig Tweak 2.4 and will not be supported in Twig Tweak 3.0', E_USER_DEPRECATED);
    $entity = \Drupal::routeMatch()
      ->getParameter($entity_type);
  }
  if ($entity) {
    $access = $check_access ? $entity
      ->access('view', NULL, TRUE) : AccessResult::allowed();
    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;
    }
  }
}