Magento – Best way to check if page is home page

homemagento2pageurl

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)

Best Answer

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