My question is regarding template caching in Craft. I want to know when does Craft actually change the cache or delete old cache.

Let's say that I am caching a chunk that just displays the entry title. Does Craft detect this change when I reload the page and hence change the cache as well? I don't know if that makes sense.

Also, I wanted some insight into the cache structure. I was caching some chunks that displayed an entry's title, description etc. The code is something like this:

{% for document in resultset %}
    {% cache using key document.entryId ~ "searchresult" %}

        {% set entry = craft.entries.id( document.entryId )[0] %}

        <div>{{ entry.title }}</div>
    {% endcache %}
{% endfor %}

When I looked into the cache tables in the database it seems like the cache is associated with an entry using the entry id.

I wanted to know how Craft knows which entry this cache relates to since the key that I have passed could have been anything and I could have cached a category or something instead of an entry. I am very confused as to how this magic is occurring.

1 Answer 1


Craft can delete caches in a few different ways:

  1. When somebody manually clears the cache via Settings->Clear Caches
  2. When Elements within {% cache %} tag are saved or deleted
  3. When a new Element is created

Regarding #2 and #3, when Craft can identify which Elements you are caching, it stores them in the craft_templatecacheelements table. If you save or delete an Element that matches one of the Element IDs that Craft has stored, Craft will clear the related template caches immediately. In the case where you are creating a new Element, it takes Craft a little bit longer to determine if that Element could be part of a related cached query and once Craft determines that is the case, will clear the cache.

Craft knows which Element IDs exist if your queries are taking place between the {% cache %} tags.

If you'd like to explore a bit more, a few places to explore would be the craft/services/TemplateCacheService.php and craft/app/etc/templating/BaseTemplate.php.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.