An interface for caching rendered templates to improve performance and reduce repeated parsing/rendering of template content.
Templates are often rendered multiple times with the same context or unchanged content. Without caching, each render would require parsing the template, processing includes, loops, conditionals, and filters, which can be computationally expensive. Implementations of TemplateCache store pre-rendered SourceCode objects for reuse, minimizing redundant work and improving response times.
Responsibilities
- Store fully-rendered SourceCode objects keyed by template identifiers.
- Provide fast retrieval of cached templates.
- Support removing or clearing cached entries to handle template updates or invalidation policies.
Usage
- A template is requested by the renderer.
- The cache is checked using get(template).
- If a cached SourceCode exists, it is returned directly.
- If not, the template is rendered, stored via put(template, sourceCode), and returned.
Example Implementation
class InMemoryTemplateCache implements TemplateCache {
final _cache = <String, SourceCode>{};
@override
SourceCode? get(String template) => _cache[template];
@override
void put(String template, SourceCode sourceCode) {
_cache[template] = sourceCode;
}
@override
void remove(String template) => _cache.remove(template);
@override
void invalidateCache() => _cache.clear();
}
Design Notes
- Caching strategy can be memory-based, disk-based, or hybrid.
- Implementations should consider thread-safety if used in concurrent environments.
- Cache invalidation is the responsibility of the implementation; for example, templates can be removed individually via remove or entirely via invalidateCache.
- Proper use of caching significantly reduces template rendering latency and CPU usage.
Integration
- Typically used in conjunction with TemplateRenderer and SourceCode to provide efficient template rendering pipelines.
- Cached SourceCode includes both raw and rendered content, along with parsed template structures for potential reuse in further processing.
Properties
- hashCode → int
-
The hash code for this object.
no setterinherited
- runtimeType → Type
-
A representation of the runtime type of the object.
no setterinherited
Methods
-
get(
String template) → SourceCode? - Retrieves a cached SourceCode object for a given template.
-
invalidateCache(
) → void - Clears all cached templates from the cache.
-
noSuchMethod(
Invocation invocation) → dynamic -
Invoked when a nonexistent method or property is accessed.
inherited
-
put(
String template, SourceCode sourceCode) → void - Stores a rendered SourceCode object in the cache for a given template.
-
remove(
String template) → void - Removes a cached SourceCode object for a given template.
-
toString(
) → String -
A string representation of this object.
inherited
Operators
-
operator ==(
Object other) → bool -
The equality operator.
inherited