Magento – Get URL of the static content folder (for backend)

adminhtmlbackendmagento2static-contenturl

Inside a block class which is being used to render a button in the admin panel, how to get the URL of the static content folder? Specifically, URL of the folder with images?

For example, in Company_Helloworld module an image for a custom button is located here:

app/code/Company/Helloworld/view/adminhtml/web/images/

Test 1

I tried this:

$url = $this->getViewFileUrl('Company_Helloworld::images/icon.png');

But it tries to retrieve the image from the Magento/backend theme:

http://example.com/pub/static/adminhtml/Magento/backend/en_US/Company_Helloworld/images/icon.png

while the image is not there, image is actually in the module's folder:

app/code/Company/Helloworld/view/adminhtml/web/images/icon.png

Test 2

And this:

$url = $this->getViewFileUrl('images/icon.png');

But it also tries to retrieve the image from the Magento/backend theme, this time without module context:

http://example.com/pub/static/adminhtml/Magento/backend/en_US/images/icon.png

Is there any way to put the image in the module and not in the backend theme?

Best Answer

Try to use:

echo $block->getViewFileUrl('Company_Helloworld::yourImage.png'); 

As a second argument of

\Magento\Framework\View\Element\AbstractBlock::getViewFileUrl($fileId, array $params = [])

you can set an array of next parameters: "module", "_secure", "theme", "area" and "locale"

Related Topic