18

我正在尝试在模板文件中检索当前页面 url,但我不知道如何在 Magento 2.0 中执行此操作。

有谁知道如何得到它?(请记住,我正在使用模板/phtml 文件)

4

3 回答 3

33

通用解决方案:可在任何地方工作,而不仅仅是来自模板:

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

从模板中,您可以更简单地完成:通过使用以下\Magento\Framework\View\Element\AbstractBlock::getUrl()方法:

$block->getUrl();

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

于 2015-11-27T10:32:26.167 回答
9

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

使用对象管理器

$urlInterface = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Framework\UrlInterface');
$urlInterface->getCurrentUrl();

使用工厂方法

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();
}
于 2017-05-01T13:26:55.193 回答
1

如果没有Object Manager,您可以使用下面的行来获取模板文件的最新 URL信息

$this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true])
于 2019-03-04T09:32:41.987 回答