Turning off Cache for Individual Blocks
Recently I have had to create a dynamic block that resides in the footer as part of an extension that brings out the star ratings schema for use in search engine listings. The schema utilises the built-in product review feature of Magento. Simply put the block within the footer will return different text depending on where you are on the website.
On the homepage the schema will bring back an aggregated result of all reviews throughout the site, on a category page the schema will show all reviews from that category and on the product page just for that product. As all these instances require the same block a problem occurred whereby the result would “stick” as you navigated around the website when cache for the website was turned on. The easy way to resolve this would be to simply turn off ”block html” caching and leave the rest of the cache enabled. However I knew there would be a better resolution and I found it in the familiar welcoming shape of XML.
Now Magento seems to cache the parent blocks of all elements, meaning that your head, header and footer are cached automatically thanks to their construct functions within their block classes. This in turn means that any child blocks are cached too. One option is to go and comment out the caching feature within these blocks but I feel this is slightly messy, instead what I found is that you can declare via XML when you want the cache to be turned off.
Here is my example on my modules layout.xml and it works wonders:
<catalog_product_view> <reference name="footer"> <action method="unsetData"><key>cache_lifetime</key></action> <action method="unsetData"><key>cache_tags</key></action> <block type="googleratings/googleratings_product" name="creare_product_ratings" as="creare_ratings" template="googleratings/product.phtml" after="-" /> </reference> </catalog_product_view>
As you can see the magic tags are the unsetData tags – and because they exist in the footer reference they tell Magento that on the product page – don’t cache the footer. This means that my block always remains dynamic!