3

I want to add a CSS class to my body tag depending on whether the current page has a breadcrumb trail. So I would rather not add a new block, since I don't need any HTML output, but just a PHP array or boolean in my PHTML file.

I tried $this->getLayout()->getBlock('breadcrumbs') without success, because the property of Mage_Page_Block_Html_Breadcrumbs which contains the trail (_crumbs) is protected.

What is the best way to achieve my goal?

2 Answers 2

2

Personally I would go with what Pronto mentioned about using rewriting the class but if you do not fancy a rewrite you can get the breadcrumb array from the block's cache key information. The cache key information contains as serialized base64 encoded version of the breadcrumbs array so the following code snippet will allow you to get the crumbs array and then you can do what you want with it.

$breadcrumbs = Mage::app()->getLayout()->getBlock('breadcrumbs');
$cacheKeyInfo = $breadcrumbs->getCacheKeyInfo();
$breadcrumb = unserialize(base64_decode($cacheKeyInfo['crumbs']));

On pages with breadcrumbs this will be an array and on other pages this will be NULL.

0

I think there's three ways to solve your problem. First is to use something like that:

if ($root = $this->getLayout()->getBlock('root')) {
    $root->addBodyClass('myclass');
}

Add this to the class that creates breadcrumbs (you probably need to overwrite it first).

Another approach is to use jQuery (or Prototype) to add your class to body should the breadcrumb DOM element exist.

Third method is to use Custom Layout Update and enter something like that:

<reference name="root">
    <action method="addBodyClass"><classname>myclass</classname></action>
</reference>

Last option of course means that you already know that this particular page has breadcrumbs (almost all pages have it, unless they've been explicitly removed).

1
  • Using your advise, I decided to rewrite Mage_Page_Block_Html_Breadcrumbs to my own block class to which I added a hasCrumbs() method. Normally objects of this kind are registered in a singleton, which enables you to create multiple blocks based on the same singleton. If this were the case, I wouldn't have to rewrite the breadcrumb block class. Unfortunately the whole system simply relies on the first instance of the breadcrumbs block, because there is no underlying model.
    – Plankje
    Commented May 25, 2014 at 13:32

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.