【问题标题】:Get the current page url in Magento 2.0在 Magento 2.0 中获取当前页面 url
【发布时间】:2016-03-01 12:43:33
【问题描述】:

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

有人知道怎么获得吗? (请记住,我正在使用模板/phtml 文件)

【问题讨论】:

    标签: magento magento2


    【解决方案1】:

    universal solution:可在任何地方工作,而不仅仅是来自模板:

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

    您可以从模板do it simplier: 使用\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

    【讨论】:

    • 你应该注入一个工厂,而不是直接使用对象管理器。
    • $block->getUrl();返回主页 URL,而不是当前页面 URL
    • @CarComp,我同意你的观点,应该首选工厂。但是单独使用Magento\Framework\UrlInterface 并没有错。当你需要一个单例时应该使用它。但是,如果您需要创建多个新 URL,则使用 Magento\Framework\UrlFactory 更有意义。
    • 得到了这个搜索结果,2021 年几乎所有的教程/指南都建议不要将ObjectManager 直接用于任何类型的实现。下面使用UrlInterface 的答案显示了获取网址的多种方法。
    【解决方案2】:

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

    使用 objectManager

    $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();
    }
    

    【讨论】:

    • 上面的工厂方法是最好的实践方法,而且绝对有效。接受的答案不是正确的方法。这应该是公认的答案。谢谢!
    【解决方案3】:

    如果没有 Object Manager,您可以使用以下行在 templates 文件中获取 current URL

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2010-11-26
      • 2015-09-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多