Custom Caching for Twig

In Superdesk Publisher we have implemented Mutlitenancy with possibility to have multiple themes (but one activated). To make process of switching, uploading and updating themes for tenant we had to came up with solution to clear cache only for one particular theme not the whole instance (with many organisations and tenants).

To achieve that we created custom Twig Cache class. It’s possible thanks Fabien Potencier change to Twig 1.22 (

Our implementations puts template cache into %kernel.cache_dir%/twig/{tenant}/themes/{theme} directory (so it’s easy to remove it when needed).

Here is the code:

Let’s put it as a service:

Now we need to enable it. To do that in Symfony we need to create Compiler Pass.

Notice that we set TenantAware cache to twig only in production env.

As you can see — you can keep that cache anywhere you need (jusy pass redis or memcached services to cache class and override write and load methods)— but keeping it in filesystem gives you php opcache support.