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();
}
}
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β¦
Top comments (0)