API Reference

Also see documentation at https://jg-rp.github.io/liquid/.

Rendering Templates

class liquid.Environment([options])

Shared configuration from which templates can be loaded and parsed.

An Environment is where you might register custom tags and filters, or store global context variables that should be included with every template.

Parameters:
  • tag_start_string (str) – The sequence of characters indicating the start of a liquid tag. Defaults to {%.

  • tag_end_string (str) – The sequence of characters indicating the end of a liquid tag. Defaults to %}.

  • statement_start_string (str) – The sequence of characters indicating the start of an output statement. Defaults to {{.

  • statement_end_string (str) – The sequence of characters indicating the end of an output statement. Defaults to }}

  • template_comments (bool) – If True, enable template comments. Where, by default, anything between {# and #} is considered a comment. Defaults to False.

  • comment_start_string (str) – The sequence of characters indicating the start of a comment. Defaults to {#. template_comments must be True for comment_start_string to have any effect.

  • comment_end_string (str) – The sequence of characters indicating the end of a comment. Defaults to #}. template_comments must be True for comment_end_string to have any effect.

  • tolerance (Mode) – Indicates how tolerant to be of errors. Must be one of Mode.LAX, Mode.WARN or Mode.STRICT. Defaults to Mode.STRICT.

  • loader (liquid.loaders.BaseLoader) – A template loader. If you want to use the builtin “render” or “include” tags, a loader must be configured. Defaults to an empty liquid.loaders.DictLoader.

  • undefined (liquid.Undefined) – A subclass of Undefined that represents undefined values. Could be one of the built-in undefined types, Undefined, DebugUndefined or StrictUndefined. Defaults to Undefined, an undefined type that silently ignores undefined values.

  • strict_filters (bool) – If True, will raise an exception upon finding an undefined filter. Otherwise undefined filters are silently ignored. Defaults to True.

  • autoescape (bool) – If True, all context values will be HTML-escaped before output unless they’ve been explicitly marked as “safe”. Requires the package Markupsafe. Defaults to False.

  • auto_reload (bool) – If True, loaders that have an uptodate callable will reload template source data automatically. For deployments where template sources don’t change between service reloads, setting auto_reload to False can yield an increase in performance by avoiding calls to uptodate. Defaults to True.

  • cache_size (int) – The capacity of the template cache in number of templates. Defaults to 300. If cache_size is None or less than 1, it has the effect of setting auto_reload to False.

  • expression_cache_size (int) – The capacity of each of the common expression caches. Defaults to 0, disabling expression caching.

  • globals (dict) – An optional mapping that will be added to the context of any template loaded from this environment. Defaults to None.

  • strip_tags (bool) –

context_depth_limit

Class attribute.The maximum number of times a render context can be extended or wrapped before a liquid.exceptions.ContextDepthError is raised.

local_namespace_limit

Class attribute. The maximum number of bytes (according to sys.getsizeof()) allowed in a template’s local namespace, per render, before a liquid.exceptions.LocalNamespaceLimitError exception is raised. Note that we only count the size of the local namespace values, not its keys.

loop_iteration_limit

Class attribute. The maximum number of loop iterations allowed before a liquid.exceptions.LoopIterationLimitError is raised.

output_stream_limit

Class attribute. The maximum number of bytes that can be written to a template’s output stream, per render, before an liquid.exceptions.OutputStreamLimitError exception is raised.

undefined

The undefined type. When an identifier can not be resolved, an instance of undefined is returned.

strict_filters

Indicates if an undefined filter should raise an exception or be ignored.

autoescape

Indicates if auto-escape is enabled.

tags

A dictionary mapping tag names to liquid.tag.Tag instances.

filters

A dictionary mapping filter names to callable objects implementing a filter’s behavior.

mode

The current tolerance mode.

cache

The template cache.

auto_reload

Indicates if automatic reloading of templates is enabled.

template_class

Environment.get_template() and Environment.from_string() return an instance of Environment.template_class. Defaults to liquid.template.BoundTemplate.

globals

A dictionary of variables that will be added to the context of every template rendered from the environment.

add_filter(name, func)

Register a filter function with the environment.

Parameters:
  • name (str) – The filter’s name. Does not need to match the function name. This is what you’ll use to apply the filter to an expression in a liquid template.

  • func (Callable[..., Any]) – Any callable that accepts at least one argument, the result of the expression the filter is applied to. If the filter needs access to the environment or render context, you probably want to make func a class that inherits from liquid.filter.Filter, and override the __call__ method. All builtin filters are implemented in this way.

Return type:

None

add_tag(tag)

Register a liquid tag with the environment. Built-in tags are registered for you automatically with every new Environment.

Parameters:

tag (Type[Tag]) – The tag to register.

Return type:

None

analyze_tags(name, *, context=None, inner_tags=None, **kwargs)

Audit template tags without parsing source text into an abstract syntax tree.

This is useful for identifying unknown, misplaced and unbalanced tags in a template’s source text. See also liquid.template.BoundTemplate.analyze().

Parameters:
  • name (str) – The template’s name or identifier, as you would use with Environment.get_template(). Use Environment.analyze_tags_from_string() to audit tags in template text without using a template loader.

  • context (Optional[liquid.Context]) – An optional render context the loader might use to modify the template search space. If given, uses liquid.loaders.BaseLoader.get_source_with_context() from the current loader.

  • inner_tags (Mapping[str, Iterable[str]]) – A mapping of block tags to a list of allowed “inner” tags for the block. For example, {% if %} blocks are allowed to contain {% elsif %} and {% else %} tags.

  • kwargs (str) –

Returns:

A tag audit including the location of any unknown tags and any unbalanced block tags.

Return type:

liquid.analyze_tags.TagAnalysis

async analyze_tags_async(name, *, context=None, inner_tags=None, **kwargs)

An async version of Environment.analyze_tags().

Parameters:
Return type:

TagAnalysis

analyze_tags_from_string(source, name='<string>', *, inner_tags=None)

Analyze tags in template source text against those registered with this environment.

Unlike template static or contextual analysis, a tag audit does not parse the template source text into an AST, nor does it attempt to load partial templates from {% include %} or {% render %} tags.

Parameters:
  • source (str) – The source text of the template.

  • name (str) – A name or identifier for the template. Defaults to “<string>”.

  • inner_tags (Mapping[str, Iterable[str]]) – A mapping of block tags to a list of allowed “inner” tags for the block. For example, {% if %} blocks are allowed to contain {% elsif %} and {% else %} tags.

Returns:

A tag audit including the location of any unknown tags and any unbalanced block tags.

Return type:

liquid.analyze_tags.TagAnalysis

from_string(source, name='', path=None, globals=None, matter=None)

Parse the given string as a liquid template.

Parameters:
  • source (str) – The liquid template source code.

  • name (str) – Optional name of the template. Available as Template.name. Defaults to the empty string.

  • path (str, pathlib.Path) – Optional path or identifier to the origin of the template. Defaults to None.

  • globals (dict) – An optional mapping of context variables made available every time the resulting template is rendered. Defaults to None.

  • matter (Optional[Mapping[str, object]]) – Optional mapping containing variables associated with the template. Could be “front matter” or other meta data.

Returns:

A parsed template ready to be rendered.

Return type:

liquid.template.BoundTemplate

get_template(name, globals=None)

Load and parse a template using the configured loader.

Parameters:
  • name (str) – The template’s name. The loader is responsible for interpreting the name. It could be the name of a file or some other identifier.

  • globals (Optional[Mapping[str, object]]) – A mapping of context variables made available every time the resulting template is rendered.

Returns:

A parsed template ready to be rendered.

Return type:

liquid.template.BoundTemplate

Raises:

liquid.exceptions.TemplateNotFound: if a template with the given name can not be found.

async get_template_async(name, globals=None)

An async version of get_template.

Parameters:
Return type:

BoundTemplate

parse(source)

Parse the given string as a liquid template.

More often than not you’ll want to use Environment.from_string() instead.

Parameters:

source (str) –

Return type:

ParseTree

liquid.Template(source: str[, options])

Returns a liquid.template.BoundTemplate, automatically creating an Environment to bind it to.

Other than source, all arguments are passed to the implicit Environment, which might have been cached from previous calls to Template().

Parameters:
  • source (str) – A Liquid template source string.

  • tag_start_string (str) – The sequence of characters indicating the start of a liquid tag. Defaults to {%.

  • tag_end_string (str) – The sequence of characters indicating the end of a liquid tag. Defaults to %}.

  • statement_start_string (str) – The sequence of characters indicating the start of an output statement. Defaults to {{.

  • statement_end_string (str) – The sequence of characters indicating the end of an output statement. Defaults to }}

  • template_comments (bool) – If True, enable template comments. Where, by default, anything between {# and #} is considered a comment. Defaults to False.

  • comment_start_string (str) – The sequence of characters indicating the start of a comment. Defaults to {#. template_comments must be True for comment_start_string to have any effect.

  • comment_end_string (str) – The sequence of characters indicating the end of a comment. Defaults to #}. template_comments must be True for comment_end_string to have any effect.

  • tolerance (Mode) – Indicates how tolerant to be of errors. Must be one of Mode.LAX, Mode.WARN or Mode.STRICT. Defaults to Mode.STRICT.

  • undefined (Undefined) – A subclass of Undefined that represents undefined values. Could be one of the built-in undefined types, Undefined, DebugUndefined or StrictUndefined. Defaults to Undefined, an undefined type that silently ignores undefined values.

  • strict_filters (bool) – If True, will raise an exception upon finding an undefined filter. Otherwise undefined filters are silently ignored. Defaults to True.

  • autoescape (bool) – If True, all context values will be HTML-escaped before output unless they’ve been explicitly marked as “safe”. Requires the package Markupsafe. Defaults to False.

  • auto_reload (bool) – If True, loaders that have an uptodate callable will reload template source data automatically. For deployments where template sources don’t change between service reloads, setting auto_reload to False can yield an increase in performance by avoiding calls to uptodate. Defaults to True.

  • cache_size (int) – The capacity of the template cache in number of templates. Defaults to 300. If cache_size is None or less than 1, it has the effect of setting auto_reload to False.

  • expression_cache_size (int) – The capacity of each of the common expression caches. Defaults to 0, disabling expression caching.

  • globals (dict) – An optional mapping that will be added to the context of any template loaded from this environment. Defaults to None.

  • strip_tags (bool) –

Return type:

BoundTemplate

class liquid.template.BoundTemplate(env, parse_tree, name='', path=None, globals=None, matter=None, uptodate=None)

A liquid template that has been parsed and is bound to a liquid.Environment.

You probably don’t want to instantiate BoundTemplate directly. Use liquid.Environment.from_string() or liquid.Environment.get_template() instead.

Parameters:
  • env (liquid.Environment) – The environment this template is bound to.

  • parse_tree (liquid.ast.ParseTree) – The parse tree representing this template.

  • name (Optional[str]) – Optional name of the template. Defaults to an empty string.

  • path (Optional[Union[str, Path]]) – Optional origin path or identifier for the template.

  • globals (Optional[Dict[str, object]]) – An optional mapping of context variables made available every time the resulting template is rendered. Defaults to None.

  • matter (Optional[Mapping[str, object]]) – Optional mapping containing variables associated with the template. Could be “front matter” or other meta data.

  • uptodate (Optional[Callable[[], bool]]) – Optional callable that will return True if the template is up to date, or False if it needs to be reloaded. Defaults to None.

name

The template’s name. As it would have been passed to liquid.Environment.get_template().

globals

A dictionary of variables that will be added to the context of every template rendered from the environment.

analyze(follow_partials=True, raise_for_failures=True)

Statically analyze this template and any included/rendered templates.

Parameters:
  • follow_partials (bool) – If True, we will try to load partial templates and analyze those templates too. Default’s to True.

  • raise_for_failures (bool) – If True, will raise an exception if an ast.Node or expression.Expression does not define a children() method, or if a partial template can not be loaded. When False, no exception is raised and a mapping of failed nodes and expressions is available as the failed_visits property. A mapping of unloadable partial templates is stored in the unloadable_partials property.

Returns:

A object containing analysis results.

Return type:

liquid.template.TemplateAnalysis

async analyze_async(follow_partials=True, raise_for_failures=True)

An async version of analyze().

Parameters:
  • follow_partials (bool) –

  • raise_for_failures (bool) –

Return type:

TemplateAnalysis

analyze_with_context(*args, **kwargs)

Analyze a path through this template’s syntax tree given some context data.

Unlike analyze(), this form of template analysis does perform a render, capturing template variables as we go.

Python Liquid does not currently support template introspection from within a render context or Expression object. Meaning line numbers and template names are not available. Only variable names are reported along with the number of times they were referenced.

It’s also, using this method, not currently possible to detect names added to a block’s scope. For example, forloop.index will be included in the results object if referenced within a for loop block.

Accepts the same arguments as render().

Returns:

Contextual analysis results.

Return type:

liquid.template.ContextualTemplateAnalysis

Parameters:
  • args (Any) –

  • kwargs (Any) –

async analyze_with_context_async(*args, **kwargs)

An async version of analyze_with_context().

Parameters:
  • args (Any) –

  • kwargs (Any) –

Return type:

ContextualTemplateAnalysis

render(*args, **kwargs)

Render the template with args and kwargs included in the render context.

Accepts the same arguments as the dict constructor.

Parameters:
  • args (Any) –

  • kwargs (Any) –

Return type:

str

async render_async(*args, **kwargs)

An async version of liquid.template.BoundTemplate.render().

Parameters:
  • args (Any) –

  • kwargs (Any) –

Return type:

str

render_with_context(context, buffer, *args, partial=False, block_scope=False, **kwargs)

Render the template using an existing context and output buffer.

args and kwargs are passed to the dict constructor. The resulting dictionary is added to the render context.

Parameters:
  • context (Context) – A render context.

  • buffer (TextIO) – File-like object to which rendered text is written.

  • partial (bool) – If True, indicates that the current template has been included using either a “render” or “include” tag. Defaults to False.

  • block_scope (bool) – If True, indicates that assigns, breaks and continues from this template will not leak into the parent context. Defaults to False.

  • args (Any) –

  • kwargs (Any) –

Return type:

None

async render_with_context_async(context, buffer, *args, partial=False, block_scope=False, **kwargs)

An async version of render_with_context.

Parameters:
  • context (Context) –

  • buffer (TextIO) –

  • args (Any) –

  • partial (bool) –

  • block_scope (bool) –

  • kwargs (Any) –

Return type:

None

Template Analysis

class liquid.template.TemplateAnalysis(*, variables, local_variables, global_variables, failed_visits, unloadable_partials, filters, tags)

The result of analyzing a template’s tags, filters and variables using BoundTemplate.analyze().

Each of the following properties is a dictionary mapping variable, tag or filter names to a list of tuples. Each tuple holds the location of a reference to the name as (<template name>, <line number>). If a name is referenced multiple times, it will appear multiple times in the list. If a name is referenced before it is “assigned”, it will appear in local_variables and global_variables.

Variables:
  • variables – All referenced variables, whether they are in scope or not. Including references to names such as forloop from the for tag.

  • local_variables – Template variables that are added to the template local scope, whether they are subsequently used or not.

  • global_variables – Template variables that, on the given line number and “file”, are out of scope or are assumed to be “global”. That is, expected to be included by the application developer rather than a template author.

  • failed_visits – Names of AST Node and Expression objects that could not be visited, probably because they do not implement a children method.

  • unloadable_partials – Names or identifiers of partial templates that could not be loaded. This will be empty if follow_partials is False.

  • filters – All filters found during static analysis.

  • tags – All tags found during static analysis.

Parameters:
  • variables (Refs) –

  • local_variables (Refs) –

  • global_variables (Refs) –

  • failed_visits (NameRefs) –

  • unloadable_partials (NameRefs) –

  • filters (NameRefs) –

  • tags (NameRefs) –

class liquid.template.ContextualTemplateAnalysis(*, all_variables, local_variables, undefined_variables, filters)

The result of analyzing a template’s filters and variables using BoundTemplate.analyze_with_context().

Each of the following properties is a dictionary mapping variable or filter names to the number of times that variable was referenced.

Variables:
  • all_variables – All variables references along a path through the template’s syntax tree.

  • local_variables – The names of variables assigned using the built-in assign capture, increment or decrement tags, or any custom tag that uses Context.assign().

  • undefined_variables – The names of variables that could not be resolved. If a name is referenced before it is assigned, it will appear in undefined and assigns.

  • filters – Names of filters found during contextual analysis.

Parameters:
  • all_variables (Dict[str, int]) –

  • local_variables (Dict[str, int]) –

  • undefined_variables (Dict[str, int]) –

  • filters (Dict[str, int]) –

class liquid.analyze_tags.TagAnalysis(*, env, name, tokens, inner_tags=None)

The result of analyzing a template’s tags with Environment.analyze_tags() or Environment.analyze_tags_async().

Each of the following properties maps tag names to a list of their locations. Locations are (template_name, line_number) tuples.

Note that raw tags are not included at all. The lexer converts them to text tokens before we get a chance to analyze them.

Also be aware that reported unexpected_tags don’t handle the possibility of an “inner” tag appearing in a partial template (using {% include %}), where appropriate enclosing block tags are in the parent template.

Variables:
  • all_tags – A mapping of all tags to their locations. Includes “end”, “inner” and unknown tags.

  • tags – A mapping of tag names to their locations. Excludes “end” and “inner” tags.

  • unclosed_tags – Block tags that don’t have a matching “end” tag.

  • unexpected_tags – Inner tags that are not properly enclosed by appropriate block tags. For example, an {% else %} that is not enclosed by a {% for %} or {% unless %} block.

  • unknown_tags – Tags that are unknown to the environment.

Parameters:
  • env (Environment) –

  • name (str) –

  • tokens (List[Token]) –

  • inner_tags (Optional[InnerTagMap]) –

Template Loaders

class liquid.loaders.FileSystemLoader(search_path, encoding='utf-8')

A loader that loads templates from one or more directories on the file system.

Parameters:
  • search_path (Union[str, Path, Iterable[Union[str, Path]]]) – One or more paths to search.

  • encoding (str) – Open template files with the given encoding. Defaults to "utf-8".

class liquid.loaders.FileExtensionLoader(search_path, encoding='utf-8', ext='.liquid')

A file system loader that adds a file name extension if one is missing.

Parameters:
  • search_path (Union[str, Path, Iterable[Union[str, Path]]]) – One or more paths to search.

  • encoding (str) – Open template files with the given encoding. Defaults to "utf-8".

  • ext (str) – A default file extension. Should include a leading period. Defaults to .liquid.

class liquid.loaders.DictLoader(templates)

A loader that loads templates from a dictionary mapping template names to template source strings. If the given dictionary is empty, liquid.Environment.get_template() will always raise a liquid.exceptions.TemplateNotFound exception.

Parameters:

templates (Dict[str, str]) – A dictionary mapping template names to template source strings.

class liquid.loaders.ChoiceLoader(loaders)

A template loader that will try each of a list of loaders until a template is found, or raise a liquid.exceptions.TemplateNotFound exception if none of the loaders could find the template.

Parameters:

loaders (List[BaseLoader]) – A list of loaders implementing liquid.loaders.BaseLoader.

class liquid.loaders.BaseLoader

Base template loader from which all template loaders are derived.

get_source(env, template_name)

Get the template source, filename and reload helper for a template

Parameters:
Return type:

TemplateSource

async get_source_async(env, template_name)

An async version of get_source. The default implementation delegates to get_source().

Parameters:
Return type:

TemplateSource

class liquid.loaders.TemplateSource(source, filename, uptodate, matter=None)

A Liquid template source as returned by the get_source method of a loader.

Parameters:
  • source (str) – The liquid template source code.

  • filename (str) – The liquid template file name or other string identifying its origin.

  • uptodate (Union[Callable[[], bool], Callable[[], Awaitable[bool]], None]) – Optional callable that will return True if the template is up to date, or False if it needs to be reloaded. Defaults to None.

  • matter (Optional[Mapping[str, object]]) – Optional mapping containing variables associated with the template. Could be “front matter” or other meta data.

Undefined Types

class liquid.Undefined(name, obj=<object object>, hint=None)

The default undefined type. Always evaluates to an empty string. Can be iterated over and indexed without error.

class liquid.StrictUndefined(name, obj=<object object>, hint=None)

An undefined that raises an exception for everything other than repr.

class liquid.DebugUndefined(name, obj=<object object>, hint=None)

An undefined that returns debug information when rendered.

class liquid.StrictDefaultUndefined(name, obj=<object object>, hint=None)

An undefined that plays nicely with the default filter.

Exceptions

class liquid.exceptions.Error(*args, linenum=None, filename=None)

Base class for all Liquid exceptions.

Parameters:
class liquid.exceptions.LiquidSyntaxError(*args, linenum=None, filename=None)

Exception raised when there is a parser error.

Parameters:
class liquid.exceptions.LiquidTypeError(*args, linenum=None, filename=None)

Exception raised when an error occurs at render time.

Parameters:
class liquid.exceptions.LiquidValueError(*args, linenum=None, filename=None)

Exception raised when a cast from str to int exceeds the length limit.

Parameters:
class liquid.exceptions.DisabledTagError(*args, linenum=None, filename=None)

Exception raised when an attempt is made to render a disabled tag.

Parameters:
class liquid.exceptions.NoSuchFilterFunc(*args, linenum=None, filename=None)

Exception raised when a filter lookup fails.

Parameters:
class liquid.exceptions.FilterArgumentError(*args, linenum=None, filename=None)

Exception raised when a filter’s arguments are invalid.

Parameters:
class liquid.exceptions.FilterValueError(*args, linenum=None, filename=None)

Exception raised when a filters value is invalid.

Parameters:
class liquid.exceptions.TemplateNotFound(*args, linenum=None, filename=None)

Exception raised when a template could not be found.

Parameters:
class liquid.exceptions.TemplateTraversalError(*args, linenum=None, filename=None)

Exception raised when an AST node or expression can not be visited.

Parameters:
class liquid.exceptions.ContextDepthError(*args, linenum=None, filename=None)

Exception raised when the maximum context depth is reached.

Usually indicates recursive use of render or include tags.

Parameters:
class liquid.exceptions.LocalNamespaceLimitError(*args, linenum=None, filename=None)

Exception raised when the maximum size of a render context’s local namespace has been exceeded.

Parameters:
class liquid.exceptions.LoopIterationLimitError(*args, linenum=None, filename=None)

Exception raised when the maximum number of loop iterations has been exceeded.

Parameters:
class liquid.exceptions.OutputStreamLimitError(*args, linenum=None, filename=None)

Exception raised when an output stream limit has been exceeded.

Parameters:
class liquid.exceptions.UndefinedError(*args, linenum=None, filename=None)

Exception raised by the StrictUndefined type.

Parameters: