获取Magento 2.0中的当前页面URL

Ser*_*mir 16 magento magento2

我试图在模板文件中检索当前页面URL,但我无法弄清楚如何在Magento 2.0中执行此操作.

有谁知道如何得到它?(请记住我在模板/ phtml文件中工作)

Mag*_*PRO 29

通用的解决方案:从任何地方工作,不仅从一个模板:

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

从模板中你可以更简单:使用\Magento\Framework\View\Element\AbstractBlock::getUrl()方法:

$block->getUrl();
Run Code Online (Sandbox Code Playgroud)

核心的一个例子:https://github.com/magento/magento2/blob/2.0.0/app/code/Magento/Customer/view/frontend/templates/logout.phtml#L14

  • 你应该注射一个工厂,而不是直接使用objectmanager. (3认同)
  • $嵌段>使用getURL(); 返回主页网址,而不是当前网页网址 (2认同)

Pri*_*tel 7

不要直接在文件中使用对象管理器实例

使用objectManager

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();
Run Code Online (Sandbox Code Playgroud)

使用工厂方法

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();
}
Run Code Online (Sandbox Code Playgroud)