Skip to main content

How to render a node field

Posted on May 28, 2020


You can render a node field respecting the view mode as follows:

$article; // The content entity that has the field.
$field_name; // Name of the field we want to render.

$entity_type = $article->getEntityTypeId(); // 'node'
$bundle = $article->bundle(); // 'article'
$view_mode = 'default'; // The $article view mode.
$field = $article->get($field_name);

// Get display configuration entity.
$display = \Drupal\Core\Entity\Entity\EntityViewDisplay::load($entity_type . '.' . $bundle . '.' . $view_mode);

// Get display options specific to $field_name.
$field_display_options = $display->getComponent($field_name);

// Get the content entity view builder.
$view_builder = \Drupal::entityTypeManager()->getViewBuilder($entity_type);

// Build $field render array.
$field_render = $view_builder->viewField($field, $field_display_options);

// Generate html markup.
$markup = \Drupal::service('renderer')->renderRoot($field_render);

Or simply

$field_render = $article->get($field_name)->view($view_mode);