cache - Liquid Tag Reference - 0.11.4

Tag Name cache
Version 0.11.4

Description

The cache tag can be used to cache the output of block of liquid code to improve page speed. Generally it is worth caching blocks of liquid code whose output doesn’t change much over time.

Examples

We’ve noticed that our Store’s header doesn’t change very often, but because site has lots of categories and pages, the liquid code does a lot of lookups when building the menu. This makes the page slower to load. This makes the header a good candidate for caching.

To cache the slow code, wrap the code in a cache tag block like so:

{%- cache "header" -%}
  ...slow liquid code goes here...
{%- endcache -%}

Here we have supplied a cache key to the tag with the value of “header”. The cache key should be a unique value to represent just this block of code. This is the bare minimum you need to do to implement caching. This will cache the header block for 60 seconds.

To cache it for a different length of time you can pass in the expires_in option like so:

{%- cache "header", expires_in: 90 -%}
  ...slow liquid code goes here...
{%- endcache -%}

Now the cache will expire after 90 seconds.

Above we used the value “header” for the cache key. In reality, this is not a good cache key to use because it doesn’t factor in that the header contains the Account and Cart menus. If we cache the same header for every customer, then instead of getting custom content in the account and cart menus, everyone using the Store will see the same menus. That’s not what we want, so we’re going to imporove the cache key by using the items option and passing in a list of objects or values that we want included in the cache key.

Here we have decided to pass in: current_store, current_customer, and current_cart. This ensures each combination of store, customer and cart will have its own cached content.

{%- cache "header", items: [current_store, current_customer, current_cart] -%}
  ...slow liquid code goes here...
{%- endcache -%}

If you want to take absolute control of your cache key, you can of course pass in any value you like as the initial key. For instance you could do this:

{%- capture "cache_key" -%}
  {{ current_store.id }}/{{ current_customer.id }}/{{ current_cart.id }}
{%- endcapture -%}
{%- cache cache_key -%}
  ...slow liquid code goes here...
{%- endcache -%}

This is just an example to show you what you could do. There are a number of short-cuts we’ve taken with this particular example for brevity, which make it unsuitable to use.

Back to Tag List

Back to Liquid Reference for 0.11.4

 

 
Back to Documentation