Get renderable array of a single field

Get the renderable output of a single field

Sometimes, in Drupal we have to get a render array for single field of the entity.

So we can do it with the next ways:

First way:

<?php

use Drupal\node\Entity\Node;

$node = Node::load(123);

$field = 'body';

// It can be omitted if you need use default view mode.
$view_mode = 'full';

$body = $node->get('body')->view($view_mode);

dump($body);

Second way:

<?php

use Drupal\node\Entity\Node;

$node = Node::load(123);

$field = 'body';

// It can be omitted if you need use default view mode.
$view_mode = 'full';

if ($node->hasField($field) && !$node->get($field)->isEmpty() && $node->access('view') {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder($node->getEntityTypeId());
  $body = $view_builder->viewField($node->get($field), $view_mode);
    
  dump($body);
}