nevercache
The nevercache tag allows you to prevent a block Twig code from getting saved in the full-page cache or within a cached template.
If the cache is enabled and a page is configured to be saved in the full-page cache, then the full rendered HTML for the page is saved in the cache. This helps with performance.
Some app templates, like Navigation, also save their fully rendered templates in the cache for performance reasons.
However, sometimes you need some Twig code to always run, even if the page is in the full-page cache or an app template is cached. Below are some examples of when you may want this:
- You need to output a random testimonial from a collection of testimonials.
- There is a notification bar that could be closed by a visitor, and a cookie is used to set if the notification bar shows. The display of the notification bar needs to be driven by the cookie and not saved in the cache.
- You need to show some other random content on a page.
- You need a custom navigation link to show differently if the user is logged in or not logged in.
The nevercache tag prevents the output from a block of code from being saved in the full-page cache or a cached app template. This means that if the full page or template output is cached, then this block of code will still be processed for every page load.
Because the code is processed on every page load for every visitor, you want to use this sparingly to keep performance high.
Below is a simple example.
{% nevercache %}
<p>My code here generates a random number {{ random(10) }}</p>
{% endnevercache %}
You can include macros within this tag.
If you need to import a macro, you must do it within the nevercache tag and not outside it. Any macros imported outside the nevercache tag will not be accessible within the nevercache tag.
{% nevercache %}
{% macro sayHello(name) %}
<p>Hello {{ name }}!</p>
{% endmacro %}
{% import _self as macros %}
<p>My code here generates a random number {{ random(10) }}</p>
{{ macros.sayHello('Bob') }}
{% endnevercache %}