1

I am trying to print an image using an image style that I've created in my drupal 8 theme.

I'm implementing a field template for the field collection. I have an image in my field collection, So i need a way to get the URL for a different image style of the same image.

Any effort will be appreciated.

2

mythemename.theme

use Drupal\image\Entity\ImageStyle;
use Drupal\file\Entity\File;


function mythemename_preprocess_page(&$variables) { 
// change _page to _node or _html depending on the template you are targetting.

  if (isset($variables['node'])) {
    $node = $variables['node'];
    // now you can use $node->field_something

    // Since I have yet to use field collection in D8, I'll let you figure this part out.
    // So all you gotta do is get the fid from your image field.

    // Once you get the FID 
    $file = File::load($fid);
    $uri = $file->getFileUri();
    $url_large = ImageStyle::load('large')->buildUrl($uri);
    $url_medium = ImageStyle::load('medium')->buildUrl($uri);
    $variables['large_image_style_url'] = url_large;
    $variables['medium_image_style_url'] = url_medium;
  }
}

Then in twig you can do {{ large_image_style_url }} and {{ medium_image_style_url }}

I had to do it like this, since I needed to print the image in page.html.twig. If you need yours in node.html.twig you could try the answers to How to use an image style in a Drupal 8 twig template?

1

This post describes how to render images with image styles in Drupal 8 programmatically: https://stackoverflow.com/questions/24754661/drupal-8-images-with-image-style

If you want to do it in a twig file here is another example: https://stackoverflow.com/questions/33510051/how-to-use-an-image-style-in-a-drupal-8-twig-template

  • Thanks fons but i have a field collection and an field collection image. please suggest a way to change its image style inside twig. – Ashish Deynap Jan 20 '17 at 8:13
  • Oké, I have update my answer – Fons Vandamme Jan 20 '17 at 8:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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