Caching in Twig


Introduction

This article will show you how to cache template fragments in Twig using the {% cache %} extension.

Basic Usage

The cache block expects a key and lifetime parameter. The lifetime should be defined in seconds.

A simple example might look like this:

{% cache 'example_key' 300 %}
    ...
{% endcache %}

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:

{% set post = entries('posts').first() %}

{% cache post 300 %}
    ...
{% endcache %}

The above example will cache the content at most for 300 seconds but will also invalidate should the page object be modified.

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:

{% set posts = entries('posts').get() %}

{% cache posts 300 %}
    ...
{% endcache %}