如何为自定义 Twig 扩展使用缓存

How to use caching for custom Twig extension

我正在使用 Twig 1.31 开发一个 Symfony 2.8 项目,我想通过创建扩展来向 Twig 添加自定义标签:

class AppExtension extends \Twig_Extension {
   ...
   public function getTokenParsers() {
       return array(new CustomTagTokenParser());
   }
}

class CustomTagTokenParser extends \Twig_TokenParser {
    ...

    public function parse(Twig_Token $token) { 
        return new CustomTagNode(...); 
    }

    public function getTag() {
        return `customtag`:
    }
}

class CustomTagNode extends \Twig_Node {
    ...
}

现在我可以在我的模板中使用 customtag

{# some Twig template #}
{% customtag %}
    ...some content...
{% endcustomtag %}

一切正常,我可以在扩展中更改 some content。但是,这是在渲染模板/加载页面时完成的。

由于 some content(以及扩展创建的更新结果)是静态的,因此可以轻松缓存。

如何仅在构建缓存时将 extension/tag 更新为 运行 一次,而不是在每次加载页面时更新?

根据 symfony doc:

Twig is fast because each template is compiled to a native PHP class and cached. But don't worry: this happens automatically and doesn't require you to do anything.
And while you're developing, Twig is smart enough to re-compile your templates after you make any changes. That means Twig is fast in production, but easy to use while developing.

简而言之,Twig 缓存每个模板并根据 kernel.debugkernel.environment 参数的值自动更新缓存。

如果你需要更多关于 twig 缓存内部行为的信息,你应该看看文档的这一部分:http://twig.sensiolabs.org/doc/1.x/api.html#compilation-cache

如果您需要更高级的策略,我建议您查看 https://github.com/asm89/twig-cache-extension,它提供了通过许多不同的策略仅缓存 twig 模板的给定部分的能力。