You can retrieve the full path of Module’s static asset like Images, Javascript or CSS file path using Magento 2.
If you want to get the full path of view directory for frontend or backend area, You need to use Magento\Framework\View\Asset\Repository class to achieve the task.
Let’s simple example for a demo, Our Module name is Jesadiya_Holiday with static assets available in view directory of the module.
holiday1.png file resides under the path,
app\code\Jesadiya\Holiday\view\frontend\web\images\holiday1.png
You want to get full path using Magento 2 for Image holiday1.png,
<?php namespace Jesadiya\Holiday\Model; use Exception; use Psr\Log\LoggerInterface; use Magento\Framework\View\Asset\Repository; class GetViewDirectoryPath { /** * @var LoggerInterface */ private $logger; /** * @var Repository */ private $assetRepository; public function __construct( LoggerInterface $logger, Repository $assetRepository ) { $this->logger = $logger; $this->assetRepository = $assetRepository; } /** * Get Image full path from view directory */ public function getImageFullPath() { $fileId = 'Jesadiya_Holiday::images/holiday1.png'; $params = [ 'area' => 'frontend' //for admin area its backend ]; $asset = $this->assetRepository->createAsset($fileId, $params); $imageFullPath = null; try { $imageFullPath = $asset->getSourceFile(); } catch (Exception $exception) { $this->logger->error($exception->getMessage()); } return $imageFullPath; } }
Call function using,
echo $this->getImageFullPath();
OutPut: Full Image path from view directory of image folder,
/var/www/html/magento234/app/code/Jesadiya/Holiday/view/frontend/web/images/holiday1.png
You can also fetch JS full path using the above function, You need to pass $fileId as JS path,
$fileId = ‘Jesadiya_Holiday::js/custom.js’;
Using the above way, You got the Javascript full path from the module.
You need to pass $params Array as Area code. For the Front end, pass area as frontend and Admin Area, Pass area code as backend.