I started using the {% cache %} tag and would like to know what the best practices are:


Regarding performance:

For example does it make sense..

  • ..to cache the whole template, or is it better to enclose each query separately?
  • ..to combine the cache-tag with other supported caches?
  • ..to cache non-dynamic content?


Regarding development:

I saw the tip to use: {% cache unless craft.config.devMode﻿ %}. Is there anything else to consider during development?


Generally you’ll just want to cache areas of your templates that are going to trigger a lot of database queries, or fetch a lot of data, since those are going to have the biggest hit on your site’s performance. Matrix field loops that have relationship fields inside them (Entries/Assets/etc.) are a good example, since each Matrix block is going to come with one or more DB queries.

There’s not much advantage to caching less intensive areas of your templates, and might lead to unexpected consequences, if you have anything dynamic being output that’s not pure-content, such as the logged in user’s username.


Worth mentioning that template caching does not respect the cacheMethod setting – that’s just for data caches. Template caches always go to the database, which in this case is the most performant option.

  • Thanks for the explanation. One more question: Why do the template caches go to the database? There are plugins for other CMS's which cache templates as .html files. Wouldn't sth. similar for craft enhance performance even more? – Victor In Jun 12 '14 at 23:40
  • 4
    Saving to the database provides the most efficient cache-busting logic. We save all caches in the templatecaches table, and a list of elements that are used in each cache in the templatecacheelements table, making it really easy to identify which caches should be deleted when you update/delete an element. – Brandon Kelly Jun 12 '14 at 23:43

When working with multiple environments you likely want to disable caching for all but one environment, because Craft saves the absolute url to entries/assets in the cache.

I achieved this by setting a custom variable in general.php

'craft.dev' => array(
    'cache' => true,
    'environmentVariables' => array(...),

 '' => array(
    'cache' => false,
    'environmentVariables' => array(...),

and then add a conditional to the cache function in the template

{% cache unless not craft.config.cache %}
    {# ... #}
{% endcache %}


  • 1
    Brilliant, nice work! – Jason McCallister Jun 13 '14 at 16:51
  • Isn't 'cache' => true a invalid configuration property as you mentioned in one of my questions. – KSPR Feb 23 '16 at 9:56

Your Answer

