28

I'm struggling trying to show the current URL from a PHTML in Magento 2.

Any suggestion?

5 Answers 5

65

It's working for me

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

Also instead $this you can use $block.

2
  • Worked perfectly. =D
    – user37025
    Jun 3, 2016 at 16:03
  • 2
    this is working perfectly. can we get the url without baseurl? Apr 10, 2018 at 8:51
13
$block->getRequest()->getUriString();
9

To do so you will need to use a custom block from a module and do the following:

In Magento 2, you can use the \Magento\Store\Model\StoreManagerInterface which is stored in an accessible variable $_storeManager for every class extending \Magento\Framework\View\Element\Template so most of the block classes (Template, Messages, Redirect block types but not Text nor TextList).

This way in your block, you can create the following method to get the current URL:

public function getCurrentUrl() {
    return $this->_storeManager->getStore()->getCurrentUrl();
}

Once you've done that you can call the following in your template:

$block->getCurrentUrl();
0
1

in block class:

    public function getCurrentUrl()
    {
        return $this->_urlBuilder->getCurrentUrl();
    }
0

Magento Community 2.4

your_file_name.phthml

<?php
    /** @var Magento\Framework\View\Element\Template $block */
?>
<a href="<?= $block->getIdentifier(); ?>">My Page URL</a>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.