I want check current page is home page, category page, product page & cms page in magento 2
-
in what context do you want to check this? controller? block?– Marius ♦Dec 9, 2015 at 11:02
-
Magento 1 version we use function Mage::getBlockSingleton('page/html_header')->getIsHomePage(); i want to show data pagewise like homepage,category page,product page & cms page etc– VishalDec 9, 2015 at 11:08
-
1I know that, but in order to answer this I want to know where do you want to use this in magento2. There is not global mage class in m2.– Marius ♦Dec 9, 2015 at 11:09
-
Because of the design pattern Dependency Injection. You create a module to request a resource on demand. Object manager is going against that paradigm. However, it works great but its like using Mage all over again--slow.– Chris AndersonJul 4, 2017 at 22:35
5 Answers
You can try this:
Inject an instance of \Magento\Framework\App\Request\Http
in your class constructor. If you are in a controller you don't need to do it. You can already access it like this $request = $this->getRequest()
public function __construct(
...
\Magento\Framework\App\Request\Http $request
) {
...
$this->_request = $request;
}
Then you can check if is homepage like this:
if ($this->_request->getFullActionName() == 'cms_index_index') {
//you are on the homepage
}
if ($this->_request->getFullActionName() == 'catalog_product_view') {
//you are on the product page
}
if ($this->_request->getFullActionName() == 'catalog_category_view') {
//you are on the category page
}
From inside phtml file this worked for me:
if ($this->getRequest()->getFullActionName() == 'cms_index_index') {
//you are on the homepage
}
if ($this->getRequest()->getFullActionName() == 'catalog_product_view') {
//you are on the product page
}
if ($this->getRequest()->getFullActionName() == 'catalog_category_view') {
//you are on the category page
}
Try this one:
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('Magento\Framework\App\Action\Context')->getRequest();
if ($request->getFullActionName() == 'cms_index_index') {
// is homepage
}
-
2
-
-
It's bad practice to use the Object Manager directly. Magento Official dev doc says "Magento prohibits the direct use of the ObjectManager in your code because it hides the real dependencies of a class." Jul 20, 2017 at 10:33
Try below code:
protected $_logo;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Theme\Block\Html\Header\Logo $logo,
array $data = []
)
{
$this->_logo = $logo;
parent::__construct($context, $data);
}
public function isHomePage()
{
return $this->_logo->isHomePage();
}
Using Object Manager
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$logo = $objectManager->get('Magento\Theme\Block\Html\Header\Logo');
var_dump($logo->isHomePage());
In .phtml file you can do this
if ($this->getRequest()->getFullActionName() == 'cms_index_index') {
// is homepage
}