'Get the current page url in Magento 2.0

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)



Solution 1:[1]

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();
}

Solution 2:[2]

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2