DEV Community

Punya Ruchal
Punya Ruchal

Posted on

2 1

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…

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay