Magento2 – Using getViewFileUrl on Backend and Frontend

magento2

I have a file called image.png

Folder structure:

-app
   -code
       -Roland
           -HelloWorld
               -view
                   -adminhtml
                       -web
                   -frontend
                       -web
                          -image.png

When I call this on frontend:

$this->getViewFileUrl("Roland_HelloWorld::image.png");

Result: http://localhost/magento2/pub/static/frontend/Magento/luma/en_US/Roland_HelloWorld/image.png

And the image loads fine.


When I call this on backend:

$this->getViewFileUrl("Roland_HelloWorld::image.png");

Result: http://localhost/magento2/pub/static/adminhtml/Magento/backend/en_US/Roland_HelloWorld/image.png

The image is not loading as it is not in the adminhtml/web/ folder.

Is there any way to load the static url for this asset with the frontend application area? What would be the official way, I do not want to duplicate this image into both folder?

UPDATE #1

This might be good, does anyone know better solution?

echo $this->getViewFileUrl("Roland_HelloWorld::image.png", array(
    'area'  => 'frontend',
    'theme' => 'Magento/Luma'
));

Best Answer

You can try to use base folder inside View if you want to have the one file in frontend and backend both:

-app
   -code
       -Roland
           -HelloWorld
               -view
                   -base
                       -web
                          -image.png

The next folder, view, is the area folder. Areas area a way to split individual Magento 2 applications into different areas of functionality, based on the URL. i.e. The cart application is Magento’s frontend area, the backend admin console is the adminhtml area.

So what’s the base area? This is one of those places where Magento 2 has improved on Magento 1 — the base area is a special folder that will allow you to serve your files from either the frontend or adminhtml areas. We’ll talk more about this below.

You can find more info here (source).

Related Topic