0

I have an image field on Basic Page content type with a View Mode where format = Image and Image Style = Large.

How can I write a template_preprocess_node hook to get the Image style that is based on the View mode?

Here is what I was thinking but got stuck and cannot figure out what to call.

function mymodule_preprocess_node(&$variables) {
  $variables['view_mode'] = $variables['elements']['#view_mode'];
  $node = $variables['elements']['#node'];
  if($variables['view_mode'] = 'default' && $node->hasField('field_image')){
    $fieldImage = $node->get('field_image');
    /** stuck here as I cannot find method to get the Image Style **/
    //goal
    $image_style = $fieldImage->getImageStyle() // not sure what method this would be
    $image_path = $fieldImage->entity->getFileUri();
    $image_url = ImageStyle::load($image_style)->buildUrl($image_path);
    $variables['content'][0]['image_url'] = $image_url; // this is the goal
  }

}

twig template

<div style="background-image: url('{{ content.image_url }}')"></div> 

1 Answer 1

1

It is part of the render array generated by the formatter: https://api.drupal.org/api/drupal/core%21modules%21image%21src%21Plugin%21Field%21FieldFormatter%21ImageFormatter.php/function/ImageFormatter%3A%3AviewElements/8.2.x

You can see that it is set on #image_style, so in node preprocess, that should be $variables['content'][field_imge][0]['#image_style'].

Depending on what you want to do, you could also write your own formatter or you could preprocess/alter the image_formatter template.

2
  • i have updated the question with more information. I want to use the image style to build the full path so that I can set it as a background. Commented Mar 9, 2018 at 16:42
  • Yes, then getting the image style from the render array is probably fine because I guess you need that information outside of the formatter.
    – Berdir
    Commented Mar 11, 2018 at 15:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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