Skip to content

Instantly share code, notes, and snippets.

@evgv
Last active August 19, 2021 17:29
Show Gist options
  • Save evgv/b211e27de4e567f4badaeae049727fe5 to your computer and use it in GitHub Desktop.
Save evgv/b211e27de4e567f4badaeae049727fe5 to your computer and use it in GitHub Desktop.
Magento 2. get Media URL in template file

Magento 2. Get media URL in template file

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.

Add to __construct in your class

protected $_storeManager;

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

Add new method in your class

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

Call in phtml


  <img src="<?php echo $block->getMediaUrl('wysiwyg/img.jpg') ?>" />

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

@matinict
Copy link

great

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment