Search
×
Log in or create an account
If you have an account with us, please log in.

You have no items in your shopping cart.

How to get the current URL in Magento 2 blocks and templates?

Sometimes you need to get the current URL in your Magento 2 block or templates. For this, we usually work with the getCurrentUrl() function. Let’s see what steps you need to undertake.

Step 1. First of all, you need to create a new block in your plugin. For example, we have made Block/Test.php with the following code:

<?php

namespace <Vendor>\<Module>\Block;

use Magento\Store\Model\StoreManagerInterface;

class Test extends \Magento\Framework\View\Element\Template
{
/**
* @var QuoteEmail
*/
private $storeManager;

public function __construct(
StoreManagerInterface $storeManager,
\Magento\Framework\View\Element\Template\Context $context,
array $data = []
) {
$this->storeManager = $storeManager;
parent::__construct($context, $data);
}

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


}

Step 2. Next, you need to create a template file for this block in the view/frontend/templates/ folder. In our case, we have made test.phtml. There are 2 options for how you can get the current URL parameters in the Magento template. See the example below:

<?php
//1 way
$block->escapeUrl($block->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]));
//2 way
$block->escapeUrl($block->getCurrentUrl());
?>

It’s better to use the second way, but the first is acceptable too. Don’t forget to clean the cache after saving the changes.

Rate the answer?
Back to top