Question

How would I check directly in a .phtml template if the requested page is homepage?

I would like to add conditionally a class to a given container

Was it helpful?

Solution

If you're checking which page is the homepage from your template then you're approaching Magento templating and layout incorrectly.

My approach generally is to create a block of type core/template and add that via layout to the correct layout handle.

More information can be found at this answer:

https://magento.stackexchange.com/a/30562/336

A deeper explanation of this misunderstood concept can be found at my blog here:

https://blog.philwinkle.com/the-most-misunderstood-concept-in-magento/

For an even deeper dive into Magento Layout read Alan Storm's book on the topic:

http://store.pulsestorm.net/products/no-frills-magento-layout

OTHER TIPS

You can use 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 or categorypage or productpage 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
}

Otherwise directly use in phtml file using object manager

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$request = $objectManager->get('\Magento\Framework\App\Request\Http');
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top