Skip to main content

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

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:

  1. /**
  2.  * Implements template_preprocess_page().
  3.  */
  5. function MYTHEME_preprocess_page(&$variables) {
  6.   if (isset($variables['node'])) {
  7.     $variables['page']['image_in_page'] = $variables['node']->field_image->view();
  8.   }
  9. }

Then, print the image in page.html.twig with:

  1.   {{ page.image_in_page }}

The logic above isn't checking whether the field_image exists, but should get you close.

Thanks for the assist:…