Drupal - Render a node field inside page.html.twig

After doing quite a bit more research, I was able to find enough pieces in other questions and on drupal.org to achieve what I wanted to do.

No pre-processing is needed for this answer, so no code needs to be added to your mytheme.theme file.
All of these variables are already accessible in page.html.twig by default.

To render a field's default value inside page.html.twig, you would typically use a 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 }}.

I also learned how to use some Twig conditionals for my particular issue, but that is beyond the scope of this question/answer.


There are three handy methods for working with this, all of which save you time digging in complicated render arrays.

  1. Using Display Suite (with submodule ds_extras) you can assign to the hero region a block ("block region") which is a different display mode (i.e. just one containing the hero image). Thus you get two different display modes showing at once. Note that some preprocess hooks may not fire as you might expect if you do this.

  2. The twig_tweak module greatly simplifies such tasks and can give easier twig statements for field values. Take a look at the cheat sheet for some common uses: {{ drupal_field('field_image', 'node', 1) }} The function signature is: drupalField($field_name, $entity_type, $id = NULL, $view_mode = 'default', $langcode = NULL)

  3. The twig_field_value module makes simpler twig statements. Per README.txt: <img src={{ file_url(content.field_image|field_target_entity.uri.value) }} alt={{ content.field_image|field_raw('alt') }} />

If I had known this earlier, it would have saved me a great deal of time!

Tags:

Theming

8