26

How to Get Media URL in Template file ? All the solution i found is calling Object Manager directly. My another concern, Can you ever call object manager directly as best practice ? (because in most of the solution they are using object manager)

7 Answers 7

42

You can get media url in your template file using below way but without using objectmanager you must have to define Block file with __construct() method with define storeManagerInterface in construct method.

In your phtml Block file create __construct function.

public $_storeManager;

public function __construct(\Magento\Store\Model\StoreManagerInterface $storeManager)
{
       $this->_storeManager = $storeManager;
}

In your phtml file call below method to get media url:

$mediaUrl = $this ->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

echo $mediaUrl;

This is the proper way to get media url in Magento 2.

3
  • 4
    I reckon it would be way better to make that variable protected and create a getter method to retrieve the media url instead Aug 25, 2016 at 9:49
  • If your block extends from \Magento\Framework\View\Element\Template, you already have an instance of StoreManagerInterface ($this->_storeManager).
    – Erfan
    Sep 18, 2017 at 3:00
  • I got media url . But i need to display the image corresponding to that url...If you know help me to sort out my problem. Please refer the below link magento.stackexchange.com/questions/201961/…
    – Jaisa
    Nov 18, 2017 at 5:34
17

As of 2.1, there is no direct way of getting the media URL without either:

  • calling the object manager directly (please don't do that)
  • override the block and add a new method

Rakesh mentioned one way of doing it.

Another way is to use the protected variable $_urlBuilder which is included for every block as defined in the AbstractBlock : https://github.com/magento/magento2/blob/f2d309a88298886460351c04973a4ff95c7a91c0/lib/internal/Magento/Framework/View/Element/AbstractBlock.php#L186

Thus you don't have to modify the constructor of your block and can simply add the following method:

public function getMediaUrl() {
    return $this->_urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]);
}

Then in your template you can call:

$block->getMediaUrl();
4
  • 8
    i think it's absurd that i can't just retrieve media path in .phtml directly.
    – LucScu
    Feb 17, 2017 at 9:37
  • 1
    @LucScu it might be discouraged, for sure. Probably not the best idea to reference an asset that has been uploaded and is not part of the codebase. It feels a bit nasty doing so.
    – Erfan
    Dec 28, 2018 at 7:58
  • 1
    @LucScu it is absurd. Just use the object manager. There is no benefit of using the convoluted 'best' way just to get a url... This is the real world not 'best practice' world. 'Best practices' that Magento doesn't even follow lol. My goodness Magento really is trash I hate it so much 😑
    – 00-BBB
    Feb 11, 2021 at 10:23
  • @00-BBB thats actually a wrong statement. Magento2 uses a lot of modern code styles, keeps many aspects in respect, whatsoever. Using of the Object Manager is by far the worst idea one can make - and besides that, the real coding world perfectly fits into "best practice"-approaches, if handled properly. That said, Magento2 overall is still not good - but for a lot of other reasons.
    – Max
    Apr 23, 2022 at 22:35
8

If you don't want to go to the trouble of extending \Magento\Framework\View\Element\Template, and you want your .phtml file to use the block \Magento\Framework\View\Element\Template, then you can use this shortcut:

$this->helper('Magento\Cms\Helper\Wysiwyg\Images')->getBaseUrl()
1
  • 2
    Using $this->helper() in PHTML files is deprecated and discouraged Jan 29, 2020 at 5:10
5

Edit: Please note that this was a valid and documented answer when first answered, but helpers have since now been deprecated, and so the use of the below is highly discouraged.


I'm going to use Raphael's answer and extend it - but instead of adding the method into the block class, why not create a helper and add it in there?

Start by creating a new module the usual way, and within the root, create a new folder called "Helper" and add the required code in there:

namespace YourSite\YourModule\Helper;
use Magento\Framework\UrlInterface;
class Url extends \Magento\Framework\App\Helper\AbstractHelper
{
    public function getMediaPath() {
        return $this->_urlBuilder->getBaseUrl(['_type' => UrlInterface::URL_TYPE_MEDIA]);
    }

}

Once activated and compiled, you will be able to use it within your template file using the following method:

<?php $url = $this->helper('\YourSite\YourModule\Helper\Url'); ?>
<img src="<?php echo $url->getMediaPath() ?>wysiwyg/image.jpg" />

I hope you (and potentially others) find this of great use!

1
  • 1
    Using $this->helper() in PHTML files is deprecated and discouraged Jan 29, 2020 at 5:10
4

At least in 2.2.6, you can use Magento\Framework\UrlInterface::getDirectUrl()

    protected function buildMediaUrl($path)
    {
        return $this->urlBuilder->getDirectUrl( $path, ['_type' => UrlInterface::URL_TYPE_MEDIA]);
    }
1
  • With some small adaptions this should be the accepted answer as of today. For several reasons: it takes in a parameter (path) to build the full URL rather than having the Developer to concat a string ugly in the Phtml, its a method that should be implemented in a Block, ... By far the best answer here.
    – Max
    Apr 23, 2022 at 22:33
1

You Try this for product Image

$this->helper('Magento\Cms\Helper\Wysiwyg\Images')->getBaseUrl().'catalog/product'.$_product->getImage();
3
  • Call to helper in template file is deprecated Sep 27, 2020 at 7:39
  • 1
    @VishwasBhatnagar you write this many places. Maybe you could suggest the "corret" way to do it as well?
    – william
    Apr 15, 2021 at 13:53
  • 1
    @william Please refer to the accepted answer or top two answer to check the correct way Apr 16, 2021 at 5:40
0

To get the media URL in a template file in Magento 2 without directly calling the Object Manager, you can follow these steps:

  1. Inject the \Magento\Store\Model\StoreManagerInterface class into your block class constructor. Open the block class file (e.g., CustomBlock.php).
use Magento\Store\Model\StoreManagerInterface;

class CustomBlock extends \Magento\Framework\View\Element\Template
{
    protected $storeManager;

    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        StoreManagerInterface $storeManager,
        array $data = []
    ) {
        $this->storeManager = $storeManager;
        parent::__construct($context, $data);
    }

    // ...
}
  1. Create a public function in the block class to retrieve the media URL. Add the following code to the CustomBlock.php file:
public function getMediaUrl($file)
{
    $mediaUrl = $this->storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    return $mediaUrl . $file;
}
  1. In your template file (e.g., custom_template.phtml), you can now call the getMediaUrl function and pass the file path as a parameter to get the complete media URL.
<img src="<?php echo $block->getMediaUrl('catalog/product/image.jpg'); ?>" alt="Product Image">

By following these steps, you can retrieve the media URL in a template file without directly calling the Object Manager in Magento 2.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.