Caching
Template Caching
An in-memory template cache is included with every Environment
. Templates parsed with Environment.get_template()
, the {% render %}
tag or the {% include %}
tag are stored so as to avoid parsing them multiple times unnecessarily, should that same template be needed again. Templates parsed using Environment.from_string()
are never cached.
The default cache size is 300
(that's 300 templates). You can control the cache capacity with the cache_size
argument to Environment
or Template
. Setting cache_size
to 0
disables template caching altogether.
from liquid import Environment
env = Environment(cache_size=800)
Using an LRU policy, the default cache is most effective in situations where the same template is rendered or included multiple times in a short space of time, or when most of your templates fit in the cache.
Expression Caching
New in version 1.1.0
Expression caching is useful in situations where the same Liquid expression appears multiple times in one or more templates. Depending on the nature of your templates, expression caching can significantly improve template parsing performance.
Expression caching is disabled by default. Enable it with the expression_cache_size
argument to Environment
or Template
.
from liquid import Environment
env = Environment(expression_cache_size=80)
An Environment
will manage one cache for each of the common, built-in expression types, filtered, boolean and loop expressions. Each uses an lru_cache from Python's functools module. You can inspect cache hits, misses and currsize for each using the cache_info()
function of Environment.parse_filtered_expression_value
, Environment.parse_boolean_expression_value
and Environment.parse_loop_expression_value
.
Tests with the benchmark fixtures show that extra memory used from caching expressions is offset by the reduced size of the resulting syntax trees.
Caching Template Loaders
New in version 1.9.0
An Environment
-wide template cache does not work well with context aware loaders. This is because the environment has no way of knowing what context variables might be used to build a cache key. For this reason it is recommended to use CachingFileSystemLoader
or CachingChoiceLoader
which, by default, replace the environment cache.
from liquid import CachingFileSystemLoader
from liquid import Environment
loader = CachingFileSystemLoader("templates/", cache_size=500)
env = Environment(loader=loader)
# ...