缓存
3.2
cache
标签在 Twig 3.2 中添加。
cache
标签告诉 Twig 缓存模板片段
1 2 3
{% cache "cache key" %}
Cached forever (depending on the cache implementation)
{% endcache %}
如果您想在一定时间后过期缓存,请通过 ttl()
修饰符指定以秒为单位的过期时间
1 2 3
{% cache "cache key" ttl(300) %}
Cached for 300 seconds
{% endcache %}
缓存键可以是任何不使用以下保留字符 {}()/\@:
的字符串;一个好的做法是在键中嵌入一些有用的信息,以便在必须刷新缓存时自动过期
- 为每个缓存指定一个唯一的名称,并像模板一样对其进行命名空间划分;
- 嵌入一个整数,每当模板代码更改时,您都会递增该整数(以自动使所有当前缓存失效);
- 嵌入一个唯一的键,每当模板代码中使用的变量发生更改时,该键都会更新。
例如,我将使用 {% cache "blog_post;v1;" ~ post.id ~ ";" ~ post.updated_at %}
来缓存博客内容模板片段,其中 blog_post
描述模板片段,v1
表示模板代码的第一个版本,post.id
表示博客文章的 ID,而 post.updated_at
返回一个时间戳,表示博客文章上次修改的时间。
使用这种命名缓存键的策略可以避免使用 ttl
。 这就像使用“验证”策略而不是像我们对 HTTP 缓存所做的那样使用“过期”策略。
如果您的缓存实现支持标签,您还可以标记您的缓存项
1 2 3 4 5 6 7
{% cache "cache key" tags('blog') %}
Some code
{% endcache %}
{% cache "cache key" tags(['cms', 'blog']) %}
Some code
{% endcache %}
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 }}
注意
cache
标签是 CacheExtension
的一部分,默认情况下未安装。 请先安装它
1
$ composer require twig/cache-extra
在 Symfony 项目中,您可以通过安装 twig/extra-bundle
来自动启用它
1
$ composer require twig/extra-bundle
或者在 Twig 环境中显式添加扩展
1 2 3 4
use Twig\Extra\Cache\CacheExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new CacheExtension());
如果您不使用 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()));
}
}
});