Magento2: Get Media URL In Template File (Without direct Calling Object Manager )

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 mediaurl,

$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.


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();

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()