Magento2 URL重定向和URL生成器

2018年11月6日 浏览量 23 1 min read
Magento2 URL重定向和URL生成器

在这篇博客中,我们将学习在magento2中使用的不同类型的url重定向。基本上,我们使用两种类型的重定向:

1.定向到上一页

2.定向到任何URL

好吧,让我们从第一个开始。为了从magento2中的自定义控制器重定向到上一页,我们需要在控制器中添加以下代码:

namespace Magease\Hello\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Actionname name extends \Magento\Framework\App\Action\Action
{ public function execute() { $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); $resultRedirect->setUrl($this->_redirect->getRefererUrl()); return $resultRedirect; } }

这里,我们首先通过调用create()创建ResultFactory实例,然后我们使用setURL()方法重定向到另一个URL,在setUrl()方法中,我们传递所需的URL。在这里,我们需要将控制器重定向到上一页,并将$this->_redirect->getRefererUrl()作为参数传递。

现在,让我们了解一下另一种类型的重定向,我们需要将自定义控制器重定向到任何所需的URL。这有多种实现方法,在这里我们将展示两种简单的方法

1.这种方法与上述方法很接近只有细微的变化,如下:

namespace Magease\Hello\Controller\Index;
use Magento\Framework\Controller\ResultFactory;
class Actionname name extends \Magento\Framework\App\Action\Action
{
    public function execute()
    {
        $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
        // Your code
        $resultRedirect->setPath('magease/index/add');
        return $resultRedirect;
    }
}

这里,我们用setPath替换了方法setUrl(),并传递给了我们要重定向的URL。

2.你也可以在magento的几个核心文件中找到重定向的方法。它比前一个复杂,但是非常简单。只需在自定义控制器中使用以下代码:

return $this->resultRedirectFactory->create()->setPath('magease/index/add/', ['_current' => true]);

如果我们使用[‘_current’ => true],那么通过查询字符串传递的对象将保留在重定向的URL中,但是如果我们不使用[‘_current’ => true]或使用 [‘_current’ => false],那么对象将不会在重定向URL中传递。

 

URL生成器

假设我们想使用锚标记或类似标记从一个页面重定向到另一个页面,那么我们需要将href属性设置为需要重定向到的URL。在这里,我们不应该使用像http://127.0.0.1/magento2/index.php/magease/index/add/ Magento 2附带URL生成器的概念,它构建了要使用的控制器的实际URL,我们只能使用:

$this->_urlBuilder->getUrl("magease/index/add/")

如果我们输出它,那么我们将获得URL: http://127.0.0.1/magento2/index.php/magease/index/add/。此方法在某种程度上类似于magento 1的经典方法Mage::getUrl()。

Previous article:
Next article:
Comments
发表评论,留下你的足迹
我们不会公开你的邮箱地址

是否允许我们在发布新内容或者进行促销活动向您发送消息?

Remind me later

Thank you! Please check your email inbox to confirm.

Oops! Notifications are disabled.

© 2014-2023 www.magease.com. All Rights Reserved. 寰云网络 版权所有    鲁ICP备 14014975号-1