Magento 2 : Get pub/static File Path

As @Khoa TruongDinh states you can use the Magento\Framework\View\Asset\Repository to get a file class Magento\Framework\View\Asset\File, which you can then use to get various data.

/** @var `Magento\Framework\View\Asset\Repository $assetRepository **/
 $asset = $this->assetRepository->createAsset('Magento_Catalog::images/image.png');
 $asset = $this->assetRepository->createAsset('My_Module::images/image.png');

To get asset in your theme folder app/design/frontend/VENDOR/THEME/web simply strip the module name as below....

$asset = $this->assetRepository->createAsset('images/image.png');

See Magento\Framework\View\Asset\File for functions you can use to get file data.

// Get the file url
$asset->getUrl();

// Get the file path
$asset->getFilePath();

// Get the content of the file
$asset->getContent();

In our block, we should try with:

$block->getViewFileUrl('/')

enter image description here

Take a look:

  • vendor/magento/module-backend/view/adminhtml/templates/page/js/require_js.phtml

  • vendor/magento/module-theme/view/frontend/templates/page/js/require_js.phtml

EDIT: we can use Magento\Framework\View\Asset\Repository

For example: your image is under : app/code/Vendor/Module/view/frontend/web/images/image.png

/** @var `Magento\Framework\View\Asset\Repository $assetRepository **/

$this->assetRepository->getUrlWithParams('Vendor_Module::images/image.png', $params);

See more here: Magento 2 Get image Url in controller or helper?

Tags:

Magento2

Paths