Sitecore custom sublayout cache key

Out the box, sitecore offers several options for caching the output of sublayouts. Some of the options you have for this are things like ‘vary by querystring’ and ‘vary by data’. This post will demonstrate how to setup custom sublayout cache keys.

Behind the scenes Sitecore builds up a cache key by appending together information from the current request based on the parameters selected in the caching options. The result of this being the cache key is longer, the more permutations you select.

For typical builds, the out the box options cover all scenarios however what do you do if you need to customise this?

In a recent project we exploited * (or wildcard) items so we could accomodate data fed from an external api. This would map known url patterns to one node in the tree, allowing the presentation components on the page to be set in sitecore but the data in the body content be fed from and external system. The mvc routing dll solves the same problem in a similar fashion.

With the default cache options we ran into the issue that the cache key for each wildcard page would always be the same since the ‘vary by data’ option used the items id, rather than the dynamic url we were assigning. Essentially every page would share the cache key for the * node.

Solution
There are only two steps needed for this implementation:

  1. Create custom implementation of a sublayout
  2. Create custom sublayout factory

Custom sublayout

To use this on the front end, you would then embed in the markup using:

If you want sublayouts instantiated from Sitecore to make use of your new type, you need to update the sublayout renderingControl in the config:

And finally the new rendering type:

In the example above the new sublayout is used for wildcard items as well as items which match an MVCRoute – this is some new functionality currently being developed by Steven Pope @ Sitecore UK.

5 thoughts on “Sitecore custom sublayout cache key

  1. Interesting post!
    I’ve done something similar here but you are overriding more methods and apparently setting sublayout’s properties dynamically via reflection. Pretty sweet. What are the overloaded GetDesignTimeHtmlParameters() and GetDesignTimeLiveControl() properties for?

    • I think it may be due to some over zealous reflectoring. I’ll check the source tomorrow and update…
      It looks like both solutions are v similar – proves it must work 🙂

      Thanks for the feedback!

      • Now updated for slightly simpler implementation of RenderingType – rather than inheriting from RenderingType, it inherits from SublayoutRenderingType

Leave a Reply

Your email address will not be published. Required fields are marked *