A while back I wrote a post on using Context Variables as a templating cache. When I came across some requirements to cache data between templates on a recent project I revisited this concept, but found some limitations with Context Variables which I had not realized before. As such I ended up implementing a different approach to caching
Contrary to my original understanding, Context Variables are not a Publish Transaction scoped bucket of data. In particular if you set a context variable in a Component Template it will not be available in the Page Template, as the Context Variables in the Component Template are actually a copy of those from the Page Template so changes get ‘lost’.
This in itself doesn’t have to be a problem with a bit of creativity; thanks to Dom Cronin for showing me the light. My problem however, was I wanted to share data between the different dynamic templates rendered when a component was published. Using Context Variables there is no way to accomplish this.
I started playing around with the .NET 4.0 introduced Caching API, which allows your programs to spin up their own caches and found that it was simple to create a memory cache which can be used by the publishing process and use this to share the data instead.
You can find the full code here, but here are some highlights:
- Implemented as extension methods on
Tridion.ContentManager.Templating.PublishingContextfor ease of use (eg
- Cache entries are scoped to the publish transaction so data will not leak outside of this scope
- Any object can be cached, but convenience methods added for caching/pushing package items – as often what you want to do is push something into the package and cache it.
- Additional methods added for caching and retrieving full rendered Output – useful if like me you have multiple dynamic CTs rendering the same component with the same output (DD4T compressed JSON)