cache
¶
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 %}
|
缓存键可以是不使用以下保留字符的任何字符串 {{}}()/\@:
;较好的做法是在key中嵌入一些有用的信息,允许缓存在必须刷新时自动过期:
- 给每个缓存一个唯一的名称和命名空间,就像你的模板一样;
- 嵌入一个每当模板代码更改时递增的整数(以自动使所有当前缓存无效);
- 嵌入一个唯一键,每当模板代码中使用的变量更改时,该键都会更新。
例如,我会使用 {{% 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环境中显式添加扩展::
use Twig\Extra\Cache\CacheExtension;
$twig = new \Twig\Environment(...);
$twig->addExtension(new CacheExtension());
如果您没有使用symfony,则还必须注册扩展运行时::
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()));
}
}
});