4

I make my first steps with Drupal 8. I have a site with a header image. On a specific content type "Blog" I want to replace the standard header image with a node specific header image. So in the content type "Blog" i made a image field "field_headerimage". I also made it possible to make a content type specific page.html.twig, see https://drupal.stackexchange.com/a/141397/31981. This works.

Problem: I want to render field_headerimage in page.html.twig. There is a "node" variable, but it seems like this values aren't able to render.

2
  • Since you are at the page level I think the most correct thing to do would be to create a block that contains the field(s) you want. As for how to create that block that's another matter and I'm not sure what solutions are available now. Something based on tokens might be good if available.
    – star-szr
    Commented Nov 1, 2015 at 18:14
  • Thanks for your comment. Yes, with a View I can maybe do something like this. But it's not nice and i have access to the node object in the page template, so i want to do it "the nice way" :) Commented Nov 1, 2015 at 18:49

1 Answer 1

5

I would say that the Twig-ish way is to create a custom filter. The Drupal-ish way is to use a hook_preprocessor. The general idea of the MVC rewrite is to keep logic out of the templates. I couldn't see how to add Twig filters in Drupal 8 (anyone?) so I'll go with preprocessor.

Drupal 8 preprocessor

In your theme's template.php:

function mytheme_preprocess_page(&$variables) {
  if ( $variables['node'] ) {
    $node = $variables['node'];
    // Optionally limit by bundle type. How do you get a bundle in D8?
    // if ( $bundle != 'blog' ) return;
    // Get your image URI.
    $header_image = $node->get('headerimage')->value;
    // Just guessing here: not sure what to do but it may involve styles.
    $header_uri = $header_image->getFileUri();
    // Override the variable that normally stores the header image.
    // Not sure what that would be. Look in page.html.twig
    $variables['headerimage'] = $header_uri;
  }
} 
3
  • Thanks! In Twig, i can make {{ node.field_headerimage.entity.url }} to get the URL. But in a preprocessor i can also set an image style. Commented Nov 2, 2015 at 15:11
  • For a complete solution: I used this: url({{ file_url(node.field_headerimage.entity.uri.value) }}) Commented Feb 2, 2016 at 14:50
  • How get uri if image field is multiple ? Commented May 13, 2017 at 5:13

Not the answer you're looking for? Browse other questions tagged or ask your own question.