5

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?

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.

4

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(); ?>
  • You can also use "$this->getRequest()->getFullActionName()" in blocks using class "Magento\Framework\View\Element\Template" – 00-BBB Aug 1 at 13:57
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
  • 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. – Daan van den Bergh May 23 '18 at 12:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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