6

Is there a way to use the ImageStyle class with dependency injection instead of a static call?

I am struggling to find an example.

At the moment I have a block which is importing the class with

use Drupal\image\Entity\ImageStyle;

And then calls the load method with

ImageStyle::load('machine_name')->buildUrl($path);

But I am wondering if there's a better way to do this?

1 Answer 1

8

Yes, inject the entity_type.manager service and load it that way:

$url = $this->entityTypeManager
  ->getStorage('image_style')
  ->load('machine_name')
  ->buildUrl($path);
3
  • I must learn to type a bit faster ;)
    – user72672
    Commented May 22, 2019 at 11:19
  • +1 to you, I think I'll delete my answer as I posted right after you :)
    – user72672
    Commented May 22, 2019 at 11:23
  • It worked, thank you!
    – spiridon
    Commented May 22, 2019 at 12:03

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.