18

I am trying to retrieve the current page url in a template file, but I can't figure out how to do it in Magento 2.0.

Does anyone know how to get it? (keep in mind I am working in a template / phtml file)

Arnaud
  • 7,259
  • 10
  • 50
  • 71
Seregmir
  • 548
  • 1
  • 5
  • 16

3 Answers3

34

The universal solution: works from anywhere, not only from a template:

/** @var \Magento\Framework\UrlInterface $urlInterface */
$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();

From a template you can do it simplier: by using the \Magento\Framework\View\Element\AbstractBlock::getUrl() method:

$block->getUrl();

An example from the core: https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/view/frontend/templates/logout.phtml#L14

Makyen
  • 31,849
  • 12
  • 86
  • 121
Dmitrii Fediuk
  • 434
  • 9
  • 11
  • 3
    You should be injecting a factory, and not using the objectmanager directly. – CarComp Apr 22 '16 at 19:45
  • 3
    $block->getUrl(); returns the homepage URL, not the current page URL – Andre Nickatine Jun 06 '16 at 18:33
  • 1
    @CarComp, I agree with you that the factory should be preferred. But there is nothing wrong with using `Magento\Framework\UrlInterface` by itself. It should be used when you need a singleton. However if you need to create multiple new URLs, using `Magento\Framework\UrlFactory` makes more sense. – Jisse Reitsma Jan 23 '17 at 13:33
  • Got this search result, in 2021 almost all tutorials/guides advise against using `ObjectManager` directly for any type of implementation. Answer below that uses `UrlInterface` shows multiple ways to get Urls. – CvRChameleon Sep 30 '21 at 12:56
9

Don't use object manager instance directly in files

With objectManager

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();

With Factory Method

protected $_urlInterface;

public function __construct(
    ...
    \Magento\Framework\UrlInterface $urlInterface
    ...
) {
    $this->_urlInterface = $urlInterface;
}

public function getUrlInterfaceData()
{
    echo $this->_urlInterface->getCurrentUrl();

    echo $this->_urlInterface->getUrl();

    echo $this->_urlInterface->getUrl('test/test2');

    echo $this->_urlInterface->getBaseUrl();
}
Prince Patel
  • 2,990
  • 1
  • 21
  • 28
  • The factory method above is the best practice way to do it and definitely works. The accepted answer is not the right way to do this. This should be the accepted answer. Thanks! – Erica S. Feb 13 '20 at 16:47
1

Without Object Manager, you can use below line to get current URL on the templates file

$this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])