Caching Rendering HTML when conditional rules are applied

Applying Sitecore caching is an essential task when you build your site, It help improve your site general performance and decrease response time significantly , Output HTML cache is one of the different types of cache that Sitecore offers, I almost apply it everywhere on site rendering components.

However, If you are applying Conditional rendering on a component (Personalization) and you are setting different datasources based on some conditions, Applying Caching on that Component with "Vary by Data" option checked will not work as expected, At first i thought that Sitecore will resolve Component datasource by applying the Conditional rules before adding that to the "Cache Key", That was not the case :( .

It turned out that Sitecore uses the default datasource applied on the component to generate the Cache Key, So you will always see the "Default" version of the component on the page, And all of Conditional rules will be ignored.

I'm using MVC for the renderings layer so i had to extend 'Sitecore.Mvc.Pipelines.Response.RenderRendering.GenerateCacheKey'  class to generate the cache key with the right datasource in it , This will generate unique cache keys for each conditional rule applied on the component.

First, I have created a new template called "Advanced Caching Options" with a checkbox field in it called "VaryByPersonalizedData":

Then i add this template as base template to "Caching" Template (In /sitecore/templates/System/Layout/Sections/Caching). I will use the checkbox to check if i need to resolve the datasource by applying Conditional rules on a rendering before generating the cache key:

Then on the rendering definition item that will have Conditional rules applied later on your page, Make sure to check both "Cacheable" and "VaryByPersonalizedData" checkboxes:

Now Time to  extend "GenerateCacheKey" processor class !

As you can see above, Im checking if the current rendering definition item has the "VaryByPersonalizedData" checked, then i apply the conditional rules on the rendering to get the right datasource then concat that to the generated Cache Key.

You will need to add the following configurations to your include folder:

<configuration xmlns:patch="">



      <mvc .renderrendering="">

        <processor patch:instead="processor[@type='Sitecore.Mvc.Pipelines.Response.RenderRendering.GenerateCacheKey, Sitecore.Mvc']" type="Sitecore.SharedSource.Pipelines.Response.RenderRendering.GenerateCacheKeyWithPeronalizedDatasource, Sitecore.SharedSource">





That was it, HTML caching is working fine on personalized renderings!

Happy Caching with Sitecore!

Popular posts from this blog

Integrating Lucene.Net.Contrib.Spatial with Sitecore Search API (Geo-Spatial Search)

Sitecore Spatial/Geo Location Search Module