7

What is the most reliable way to check if current page is the home page? I need to check that in a block class and in a helper class. Searching on forums, I've found two popular ways to do this:

Method 1

The first method is almost the same that worked also in Magento 1:

/**
 * @var \Magento\Framework\UrlInterface
 */
protected $urlInt;
public function getIsHomePage()
{
    return 
        $this->urlInt->getUrl('') == $this->urlInt->getUrl('*/*/*', ['_current'=>true, '_use_rewrite'=>true]);
}

Method 2

The second method is the one I've found on stackexchange, something like:

/**
 * @var \Magento\Framework\App\RequestInterface
 */
protected $request;
public function getIsHomePage()
{
    if ($this->request->getFullActionName() == 'cms_index_index')
    {
        return true;
    }
}
  1. Which method is better? Will they both work correctly in all cases, or should I be careful in some specific cases?
  2. Which method is faster? (I understand the difference will be very small)

2 Answers 2

5

If you are looking for the CMS Home Page, Method 2 is better:

  • easier to understand
  • more explicit
  • faster, but I only mention it because you asked, the difference is insignificant

But if you want to take into consideration that the default page might be something else (for example the contact form, a certain category, or product), you should use Method 1.

enter image description here

2
  • Side note, Magento 2 already provides such method, see my answer Apr 15, 2016 at 9:20
  • 1
    I didn't consider the possibility that a non-cms route could be configured as home page, updated my answer Apr 15, 2016 at 9:30
3

On a side note, it's good to notice that the Magento\Theme\Block\Html\Header\Logo class provides a isHomePage method that looks like this:

public function isHomePage()
{
    $currentUrl = $this->getUrl('', ['_current' => true]);
    $urlRewrite = $this->getUrl('*/*/*', ['_current' => true, '_use_rewrite' => true]);
    return $currentUrl == $urlRewrite;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.