7

Magento version: 2.0.0

How to check the current page is home page in the template file? There has a global function to do it?

3 Answers 3

8

Set block content with custom function :

protected $_request;

public function __construct(
    ...
    \Magento\Framework\App\Request\Http $request,
    ...
) {
    ...
    $this->_request = $request;
    ...
}

public function isHomepage()
{

    if ($this->_request->getFullActionName() == 'cms_index_index') {
        return true;
    }
    return false;
}

Template code :

<?php  $isHome = $block->isHomepage(); ?>
1
  • You can also use "$this->getRequest()->getFullActionName()" in blocks using class "Magento\Framework\View\Element\Template"
    – 00-BBB
    Commented Aug 1, 2019 at 13:57
4

Try:

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

In addition you can use the \Magento\Theme\Block\Html\Header\Logo::isHomePage() method if you has this block in all pages.

0

You can also check

$objectManagerCms = \Magento\Framework\App\ObjectManager::getInstance();
$cmsPage = $objectManagerCms->get('\Magento\Cms\Model\Page');

echo $cmsPage->getIdentifier(); //Current CMS Page Identifier
1
  • It's bad practice to use Object Manager. Especially when the needed information can be found in Magento\Framework\App\Request\Http as mentioned by @ronak-chauhan. Commented May 23, 2018 at 12:01

Your Answer

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

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