Caching in Twig
- Posted March 27, 2017
- Developer Tools
- essentials
Related Links
Introduction
This article will show you how to cache template fragments in Twig using the {% verbatim %}{% cache %}{% endverbatim %}
extension.
Basic Usage
The cache block expects a key
and lifetime
parameter. The lifetime
should be defined in minutes.
A simple example might look like this:
{% verbatim %}{% cache 'example_key' 5 %}
...
{% endcache %}{% endverbatim %}
Auto Invalidation
Using an object as a key automatically invalidates cached content when the object is modified. In this case the lifetime will be the maximum allowed time to cache the content should the object not change before then:
{% verbatim %}{% set post = entries('posts').first() %}
{% cache post 5 %}
...
{% endcache %}{% endverbatim %}
The above example will cache the content at most for 5 minutes but will also invalidate should the post be modified in any way.
Reusing Invalidation Data
You can leverage the same data in multiple cache blocks by passing an array with a prefix value:
{% verbatim %}{% set post = entries('posts').first() %}
{% cache ['foo', post] 5 %}
...
{% endcache %}
{% cache ['bar', post] 5 %}
...
{% endcache %}{% endverbatim %}
Collection Keys
You can also use a collection as the key. In this example the cache will be invalidated if any of the objects in the collection are modified:
{% verbatim %}{% set posts = entries('posts').get() %}
{% cache posts 5 %}
...
{% endcache %}{% endverbatim %}
Query Caching
You can also cache queries from the entries
function just as you would via API using the model. Just like the above examples the cache will automatically be invalidated:
{% verbatim %}{% set posts = entries('posts').cache(5).get() %}{% endverbatim %}
The above example will cache the content at most for 5 minutes but will also invalidate should any post be modified in any way.