Caching in Twig


Related Links

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 minutes.

A simple example might look like this:

{% cache 'example_key' 5 %}
    ...
{% 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 5 %}
    ...
{% endcache %}

The above example will cache the content at most for 5 minutes but will also invalidate should the post be modified in any way.

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 5 %}
    ...
{% endcache %}

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:

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

The above example will cache the content at most for 5 minutes but will also invalidate should any post be modified in any way.


No Comments


Leave a Comment