2

In Magento 2, is it possible to generate an HTTP path to a module's front-end asset files (CSS, Javascript) using PHP?

i.e. I know it's possible to add code like the following to a layout handle XML file

<css src="foo/baz/bar.css"/>
<link src="Magento_Sales::js/bootstrap/order-create-index.js"/>

What I'm curious about is do these layout directives have direct PHP equivalents? If so, what are they. If not, is there a reasonable technique for stabling reproducing their behavior via PHP?

6

I dug through the layout rendering code and found the answer to this one myself. You can use a Magento\Framework\View\Asset\Repository to create asset objects, and then use the asset objects to get a URL.

That is, inject the Magento\Framework\View\Asset\Repository repository via automatic constructor dependency injection.

protected $assetRepository;
public function __construct(
    \Magento\Framework\View\Asset\Repository $assetRepository
)
{
    $this->assetRepository = $assetRepository;
}

Use the asset repository to create an asset object

$asset = $this->assetRepository->createAsset('Vendor_Module::path/to/file.js')

and then use the asset object to get a URL

echo $asset->getUrl();
| improve this answer | |
2

I'm not sure if there is a direct PHP equivalent but you can do this in a block very easily

$this->getViewFileUrl() . '/' . $this->getModuleName()

This will give you a path like this

http://m2.dev/pub/static/frontend/Magento/luma/en_US/Package_Module

And of course you can leave out the module name if you want to get a theme resource.

| improve this answer | |
0

Not sure if it is what you are looking for, but take a look on Magento\Framework\View\Page\Config public methods.

| improve this answer | |
0

You can use also like this create the object of assets Repository

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

$_assetRepo = $objectManager->create('Magento\Framework\View\Asset\Repository');

echo $_assetRepo->getUrl("Globaliasoft_Banner::images/t1.png");

use your module name instead of Globaliasoft_Banner.

| improve this answer | |

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.