Drupal 8: Make a node's field accessible in page.html.twig

Profile picture for user Phil Frilling
By Phil Frilling, 26 October, 2018
We had a use case where an image field needed to be used as a background image in the scope of page.html.twig. This is pretty simple with the use of template_preprocess_page(). To get the image field into the page variable use this code:

/**
 * Implements template_preprocess_page().
 */

function MYTHEME_preprocess_page(&$variables) {
  if (isset($variables['node'])) {
    $variables['page']['image_in_page'] = $variables['node']->field_image->view();
  }
}
Then, print the image in page.html.twig with:

  {{ page.image_in_page }}
The logic above isn't checking whether the field_image exists, but should get you close. Thanks for the assist: https://www.computerminds.co.uk/articles/rendering-drupal-8-fields-righ…