I have aThe following code sample will get you what you are looking for:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Sitecore.Analytics;
using Sitecore.Data;
using Sitecore.Diagnostics;
using Sitecore.Layouts;
using Sitecore.Mvc.Extensions;
using Sitecore.Mvc.Pipelines.Response.RenderRendering;
using Sitecore.Mvc.Presentation;
using Sitecore.Rules.ConditionalRenderings;
namespace MyNamespace.Pipelines.MvcRenderRendering
{
public class GenerateCacheKey : Sitecore.Mvc.Pipelines.Response.RenderRendering.GenerateCacheKey
{
/// <summary>
/// Holds the name of the Sitecore checkbox field that controls whether the cache key
/// should vary by favorite color of the user/visitor
/// </summary>
private const string VaryByFavoriteColorFieldName = "VaryByFavoriteColor";
/// <summary>
/// Generates the cache key with all caching variance parts added
/// </summary>
protected override string GenerateKey(Rendering rendering, RenderRenderingArgs args)
{
var cacheKey = base.GenerateKey(rendering, args);
// if set to vary caching by favorite color add the favorite color part to the key
if (IsCacheVaryByFavoriteColor(rendering))
{
cacheKey += GetFavoriteColorPart();
}
return cacheKey;
}
/// <summary>
/// Checks if the rendering is set to vary caching by favorite color
/// </summary>
private bool IsCacheVaryByFavoriteColor(Rendering rendering)
{
// so long as the VaryByFavoriteColor checkbox field exists and is checked, we should be varying by favorite color
return rendering.RenderingItem.InnerItem[VaryByFavoriteColorFieldName] != null && rendering.RenderingItem.InnerItem[VaryByFavoriteColorFieldName] == "1";
}
/// <summary>
/// Gets the part of the cache key that will vary by favorite color
/// </summary>
public virtual string GetFavoriteColorPart()
{
...logic for getting favorite color from user profile or from tracking session...
return !string.IsNullOrEmpty(favoriteColor)
? $"_#favoriteColor:{favoriteColor}" // adds a string unique to the favorite color to the cache key
: string.Empty;
}
}
}
Note that Ithe above processor should replace the native GenerateCacheKey
processor and you will addneed to this postadd the VaryByFavoriteColor
field in Sitecore. To add the field, once I findcreate a new template, named something like "Extended Caching", and add a field section to it, named Caching
. Add a checkbox field to the new section, named VaryByFavoriteColor
and set the field's title text to "Vary By Favorite Color" (capital "B" in my archives"By" for consistency with Sitecore). Finally, add your new template to the
Base Templates of the /sitecore/templates/System/Layout/Sections/Caching
template. This is one of the few times that it is appropriate to modify a native Sitecore template.
Once you have completed the above, you should be able to set global caching settings on the rendering.