Get the current page url in Magento 2.0

Seregmir picture Seregmir · Nov 27, 2015 · Viewed 31k times · Source

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)

Answer

Mage2.PRO picture Mage2.PRO · Nov 27, 2015

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