Magento 2.1 Media path in .phtml file

Usage of Object Manager is discouraged as per Magento's coding standards. In a template file, we can get the media URL using the following code:

$this->helper('\Magento\Cms\Helper\Wysiwyg\Images')->getBaseUrl()

As per the Magento's recommendation, the document root of your website should be outside pub directory during development and it should be inside pub directory when moved to production.

Hence we cannot hard code the pub directory while getting media URL in the template files. The above code will give you the correct media URL irrespective of your document root location.


you can get media path by $object method

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
                    ->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

factories method

<?php
    namespace Namespace\Modulename\Block;
    use Magento\Framework\ObjectManagerInterface;

    class Banners extends Template
    {

        protected $objectManager;
        public function __construct( 
            ....... 
            ObjectManagerInterface $objectManager
                       ...) {

                    ...........
                    $this->objectManager = $objectManager;

                    ...............
        }
        public function getMediaUrl(){

            $media_dir = $this->objectManager->get('Magento\Store\Model\StoreManagerInterface')
                ->getStore()
                ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

            return $media_dir;
        }
    }
    ........
?>

in phtml file

<?php echo $block->getMediaUrl(); ?>

Get media path by objectManager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
echo $objectManager->get('Magento\Store\Model\StoreManagerInterface')
                    ->getStore()
                    ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);

Get media path by Dependency Injection

protected $_storeManager;

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

public function getMediaUrl()
{
    $mediaUrl = $this->_storeManager
                     ->getStore()
                     ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    return $mediaUrl;
}

Now call function getMediaUrl() in phtml

<?php echo $block->getMediaUrl(); ?>

Tags:

Media

Magento2