我试图在模板文件中检索当前页面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
$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)