I am working on a Symfony
2.8 project using Twig
1.31, and I would like to add a custom tag to Twig
by creating an extension:
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 {
...
}
Now I can use the customtag
within my templates:
{# some Twig template #}
{% customtag %}
...some content...
{% endcustomtag %}
This all works fine, and I can alter some content
within the extension. However, this is done when rendering the template / when loading the page.
Since some content
(as well as the updated result created by the extension) is static, this could easily be cached.
How to update the extension/tag to run only once, when building the cache and not on every page load?
According to the 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.
In short, Twig caches every templates and renews the cache automatically depending on the value of the kernel.debug
and kernel.environment
parameters.
If you need some more informations about the internal behavior of twig caching, you should have a look this part of the doc: http://twig.sensiolabs.org/doc/1.x/api.html#compilation-cache
If you need a more advanced strategy, I suggest you to have a look at https://github.com/asm89/twig-cache-extension which provides the ability to cache only given parts of twig templates through a lot of different strategies.