3

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

4

2 Answers 2

2

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

1
  • 1
    The question is asking about Magento 2, but these answers all relate to Magento 1.
    – Ryre
    Commented Mar 22, 2017 at 19:33
2

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');

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.