0

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?

2

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

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

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.