Magento2 – Get Media URL in Template File Without Object Manager

magento-2.1magento2mediaobject-managertemplate

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)

Best Answer

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.

Related Topic