You are here

public function TwigExtension::drupalField in Twig Tweak 8.2

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

Returns the render array for a single entity field.

Parameters

string $field_name: The field name.

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 field.

string $langcode: (optional) Language code to load translation.

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

Return value

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

File

src/TwigExtension.php, line 668

Class

TwigExtension
Twig extension with some useful functions and filters.

Namespace

Drupal\twig_tweak

Code

public function drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $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) {
    $entity = \Drupal::service('entity.repository')
      ->getTranslationFromContext($entity, $langcode);
    $access = $check_access ? $entity
      ->access('view', NULL, TRUE) : AccessResult::allowed();
    if ($access
      ->isAllowed()) {
      if (isset($entity->{$field_name})) {
        $build = $entity->{$field_name}
          ->view($view_mode);
        CacheableMetadata::createFromRenderArray($build)
          ->merge(CacheableMetadata::createFromObject($access))
          ->merge(CacheableMetadata::createFromObject($entity))
          ->applyTo($build);
        return $build;
      }
    }
  }
}