public function TwigExtension::drupalField in Twig Tweak 8
Same name and namespace in other branches
- 8.2 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.
Return value
null|array A render array for the field or NULL if the value does not exist.
File
- src/
TwigExtension.php, line 199
Class
- TwigExtension
- Twig extension with some useful functions and filters.
Namespace
Drupal\twig_tweakCode
public function drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $langcode = NULL) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
$entity = $id ? \Drupal::entityTypeManager()
->getStorage($entity_type)
->load($id) : \Drupal::routeMatch()
->getParameter($entity_type);
if ($entity) {
$access = $this
->entityAccess($entity);
if ($access
->isAllowed()) {
if ($langcode && $entity
->hasTranslation($langcode)) {
$entity = $entity
->getTranslation($langcode);
}
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;
}
}
}
}