cache

3.2

3.2

The cache tag was added in Twig 3.2.

cache タグは Twig 3.2 で追加されました。

The cache tag tells Twig to cache a template fragment:

cache タグは Twig にテンプレート フラグメントをキャッシュするように指示します。
1
2
3
{% cache "cache key" %}
    Cached forever (depending on the cache implementation)
{% endcache %}

If you want to expire the cache after a certain amount of time, specify an expiration in seconds via the ttl() modifier:

一定時間後にキャッシュを失効させたい場合は、ttl() 修飾子を使用して秒単位で失効を指定します。
1
2
3
{% cache "cache key" ttl(300) %}
    Cached for 300 seconds
{% endcache %}

The cache key can be any string that does not use the following reserved characters {}()/\@:; a good practice is to embed some useful information in the key that allows the cache to automatically expire when it must be refreshed:

キャッシュ キーは、次の予約文字 {}()/\@: を使用しない任意の文字列にすることができます。キーに有用な情報を埋め込むことをお勧めします。これにより、キャッシュを更新する必要があるときにキャッシュを自動的に失効させることができます。
  • Give each cache a unique name and namespace it like your templates;
    テンプレートのように、各キャッシュに一意の名前と名前空間を付けます。
  • Embed an integer that you increment whenever the template code changes (to automatically invalidate all current caches);
    テンプレート コードが変更されるたびにインクリメントする整数を埋め込みます (現在のすべてのキャッシュを自動的に無効にするため)。
  • Embed a unique key that is updated whenever the variables used in the template code changes.
    テンプレート コードで使用される変数が変更されるたびに更新される一意のキーを埋め込みます。

For instance, I would use {% cache "blog_post;v1;" ~ post.id ~ ";" ~ post.updated_at %} to cache a blog content template fragment where blog_post describes the template fragment, v1 represents the first version of the template code, post.id represent the id of the blog post, and post.updated_at returns a timestamp that represents the time where the blog post was last modified.

たとえば、{% cache "blog_post;v1;" を使用します。 ~ post.id ~ ";" ~post.updated_at %} はブログ コンテンツ テンプレート フラグメントをキャッシュします。blog_post はテンプレート フラグメントを表し、v1 はテンプレート コードの最初のバージョンを表し、post.id はブログ投稿の ID を表し、post.updated_at は時刻を表すタイムスタンプを返します。ブログ投稿が最後に変更された場所。

Using such a strategy for naming cache keys allows to avoid using a ttl. It's like using a "validation" strategy instead of an "expiration" strategy as we do for HTTP caches.

キャッシュ キーの名前付けにこのような戦略を使用すると、ttl の使用を避けることができます。これは、HTTP キャッシュの場合のように、「有効期限」戦略の代わりに「検証」戦略を使用するようなものです。

If your cache implementation supports tags, you can also tag your cache items:

キャッシュ実装がタグをサポートしている場合は、キャッシュ アイテムにタグを付けることもできます。
1
2
3
4
5
6
7
{% cache "cache key" tags('blog') %}
    Some code
{% endcache %}

{% cache "cache key" tags(['cms', 'blog']) %}
    Some code
{% endcache %}

The cache tag creates a new "scope" for variables, meaning that the changes are local to the template fragment:

cache タグは、変数の新しい「スコープ」を作成します。つまり、変更はテンプレート フラグメントに対してローカルです。
1
2
3
4
5
6
7
8
9
10
{% set count = 1 %}

{% cache "cache key" tags('blog') %}
    {# Won't affect the value of count outside of the cache tag #}
    {% set count = 2 %}
    Some code
{% endcache %}

{# Displays 1 #}
{{ count }}

Note

ノート

The cache tag is part of the CacheExtension which is not installed by default. Install it first:

キャッシュ タグは、デフォルトではインストールされない CacheExtension の一部です。最初にインストールします。
1
$ composer require twig/cache-extra

On Symfony projects, you can automatically enable it by installing the twig/extra-bundle:

Symfony プロジェクトでは、twig/extra-bundle をインストールすることで自動的に有効にすることができます:
1
$ composer require twig/extra-bundle

Or add the extension explicitly on the Twig environment:

または、Twig 環境で拡張機能を明示的に追加します。
1
2
3
4
use Twig\Extra\Cache\CacheExtension;

$twig = new \Twig\Environment(...);
$twig->addExtension(new CacheExtension());

If you are not using Symfony, you must also register the extension runtime:

Symfony を使用していない場合は、拡張ランタイムも登録する必要があります。
1
2
3
4
5
6
7
8
9
10
11
12
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use Symfony\Component\Cache\Adapter\TagAwareAdapter;
use Twig\Extra\Cache\CacheRuntime;
use Twig\RuntimeLoader\RuntimeLoaderInterface;

$twig->addRuntimeLoader(new class implements RuntimeLoaderInterface {
    public function load($class) {
        if (CacheRuntime::class === $class) {
            return new CacheRuntime(new TagAwareAdapter(new FilesystemAdapter()));
        }
    }
});