Magento – Set block cache lifetime for block in layout xml

block-cacheblockscachemagento2

Magento 2.1.1.

I have added custom sorting of products in catalog pages, by random order and I want my block to be dynamicall, so with every change of sorting for random the collection should be shuffled.

I would like to set cache lifetime for block in layout xml if possible. I can exclude it completly from caching using `cacheable="false", but that's not exactly I need.
I have noticed something like this:

<block class="Magento\Theme\Block\Html\Topmenu" name="catalog.topnav" template="html/topmenu.phtml" ttl="3600" before="-"/>

I am not sure how to test if it working – I set 15 seconds for my block, but actually order of product never changed.

If I find out how to set ttl for block, nice improvment would be one from here:
https://www.schmengler-se.de/en/2015/09/show-random-products-in-magento-you-are-doing-it-wrong/

First, make sure that you don’t load random products on every request. Use the cache. Even with a cache lifetime of just a few minutes, this will reduce load on a frequently visited page significantly. If you want to avoid showing the same products to the same user on a page refresh, you can cache multiple versions of the block using different cache keys and select one of the tags based on time, a counter in the session, or randomly.

The following method in a block caches 10 versions of the block and rotates them for each user. With a low cache lifetime most users will not see the same version twice:

In similiar situation I can add my block in a few versions to cache (preventing the same user watching the same order of products), but I don't know how to achieve that.

Best Answer

For Topmenu you should override \Magento\Theme\Block\Html\Topmenu:

protected function getCacheLifetime(){
    return null;
}
Related Topic