phptal:cache

This attribute causes output of entire element (including its tag) to be cached on disk and not re-evaluated until cache expires.

Note

Use of cache is beneficial only for elements that use very complex expressions, macros from external files or PHP expressions/objects that access the database. Otherwise uncached templates will be just as fast.

Content of this attribute is a duration (how long element should be kept in cache) written as number with 'd', 'h', 'm' or 's' suffix.

<div class="footer" phptal:cache="3h"></div>

<div> will be evaluated at most once per 3 hours.

Duration can be followed by optional "per" parameter that defines how cache should be shared. By default cache is shared between all pages that use that template. You can add "per url" to have separate copy of given element for every URL.

<ol id="breadcrumbs" phptal:cache="1d per url"></ol>

<ol> will be cached for one day, separately for each page.

You can add "per expression" to have different cache copy for every different value of an expression (which MUST evaluate to a string).

Note

Expression cannot refer to variables defined using tal:define on the same element.

<ul id="user-info" phptal:cache="25m per object/id"></ul>

<ul> will be cached for 25 minutes, separately for each object ID.

Warning

Be careful when caching users' private data. Cache will be shared with everyone unless you make it user-specific with per user/id or similar expression.

Instant refreshing

Instead of clearing cache, it might be a better idea to put version or last modification timestamp in the per parameter. This will cause cached template to be refreshed as soon as version/timestamp changes and no special cache clearing will be necessary.

<div phptal:cache="100d per php:news.id . news.last_modified_date"></div>

Limitations:

  • phptal:cache blocks can be nested, but outmost block will cache other blocks regardless of their freshness.

  • You cannot use metal:fill-slot inside elements with phptal:cache.