DEV Community

Punya Ruchal
Punya Ruchal

Posted on

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

We can render the node fields value in page.html.twig on two different ways.

First method

Without defining node pre-processing in mytheme.theme file. We can render a field's default value inside page.html.twig, using the following Twig variable as in {{ node.field_some_name.value }}.

If you have an image field, and want to render the URL to the image stored in that field inside the page.html.twig template, you would use {{ file_url(node.field_some_image.entity.fileuri) }}.

Finally, if you want to render the title of a node inside the page.html.twig template, you would use {{ node.label }}.

Second method

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) {
  // Define {{ field_image }} field value available in the template.  
  if (isset($variables['node'])) {
    $variables['page']['image_in_page'] = $variables['node']->field_image->view();
  }
}
Enter fullscreen mode Exit fullscreen mode

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

{{ page.image_in_page }}
Enter fullscreen mode Exit fullscreen mode

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…

Latest comments (0)