Skip to content

Rendering Templates

Environment

Environment(
    tag_start_string: str = "{%",
    tag_end_string: str = "%}",
    statement_start_string: str = "{{",
    statement_end_string: str = "}}",
    strip_tags: bool = False,
    tolerance: Mode = Mode.STRICT,
    loader: Optional[loaders.BaseLoader] = None,
    undefined: Type[Undefined] = Undefined,
    strict_filters: bool = True,
    autoescape: bool = False,
    auto_reload: bool = True,
    cache_size: int = 300,
    globals: Optional[Mapping[str, object]] = None,
    template_comments: bool = False,
    comment_start_string: str = "{#",
    comment_end_string: str = "#}",
    expression_cache_size: int = 0,
)

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.

PARAMETER DESCRIPTION
tag_start_string

The sequence of characters indicating the start of a liquid tag.

TYPE: str DEFAULT: '{%'

tag_end_string

The sequence of characters indicating the end of a liquid tag.

TYPE: str DEFAULT: '%}'

statement_start_string

The sequence of characters indicating the start of an output statement.

TYPE: str DEFAULT: '{{'

statement_end_string

The sequence of characters indicating the end of an output statement.

TYPE: str DEFAULT: '}}'

template_comments

If True, enable template comments, where, by default, anything between {# and #} is considered a comment.

TYPE: bool DEFAULT: False

comment_start_string

The sequence of characters indicating the start of a comment. template_comments must be True for comment_start_string to have any effect.

TYPE: str DEFAULT: '{#'

comment_end_string

The sequence of characters indicating the end of a comment. template_comments must be True for comment_end_string to have any effect.

TYPE: str DEFAULT: '#}'

tolerance

Indicates how tolerant to be of errors. Must be one of Mode.LAX, Mode.WARN or Mode.STRICT.

TYPE: Mode DEFAULT: STRICT

loader

A template loader. If you want to use the builtin "render" or "include" tags, a loader must be configured.

TYPE: Optional[BaseLoader] DEFAULT: None

undefined

A subclass of Undefined that represents undefined values. Could be one of the built-in undefined types, Undefined, DebugUndefined or StrictUndefined.

TYPE: Type[Undefined] DEFAULT: Undefined

strict_filters

If True, will raise an exception upon finding an undefined filter. Otherwise undefined filters are silently ignored.

TYPE: bool DEFAULT: True

autoescape

If True, all render context values will be HTML-escaped before output unless they've been explicitly marked as "safe". Requires the package Markupsafe.

TYPE: bool DEFAULT: False

auto_reload

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.

TYPE: bool DEFAULT: True

cache_size

The capacity of the template cache in number of templates. If cache_size is None or less than 1, it has the effect of setting auto_reload to False.

TYPE: int DEFAULT: 300

expression_cache_size

The capacity of each of the common expression caches. A cache_size of 0 will disabling expression caching.

TYPE: int DEFAULT: 0

globals

An optional mapping that will be added to the render context of any template loaded from this environment.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

ATTRIBUTE DESCRIPTION
context_depth_limit

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

TYPE: int

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 LocalNamespaceLimitError exception is raised. Note that we only count the size of the local namespace values, not its keys.

TYPE: Optional[int]

loop_iteration_limit

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

TYPE: Optional[int]

output_stream_limit

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

TYPE: Optional[int]

render_whitespace_only_blocks

Class attribute. Indicates if block tags that, when rendered, contain whitespace only should be output. Defaults to False, meaning empty blocks are suppressed.

TYPE: bool

undefined

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

TYPE: Type[Undefined]

strict_filters

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

TYPE: bool

autoescape

Indicates if auto-escape is enabled.

TYPE: bool

tags

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

TYPE: Dict[str, Tag]

filters

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

TYPE: Dict[str, Callable[..., Any]]

mode

The current tolerance mode.

TYPE: Mode

cache

The template cache.

TYPE: Optional[MutableMapping[Any, Any]]

auto_reload

Indicates if automatic reloading of templates is enabled.

TYPE: bool

template_class

Environment.get_template and Environment.from_string return an instance of Environment.template_class.

TYPE: Type[BoundTemplate]

globals

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

TYPE: Mapping[str, object]

add_filter

add_filter(name: str, func: Callable[..., Any]) -> None

Register a filter function with the environment.

PARAMETER DESCRIPTION
name

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.

TYPE: str

func

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 active environment or render context, use liquid.filer.with_context and/or liquid.filter.with_environment decorators.

TYPE: Callable[..., Any]

add_tag

add_tag(tag: Type[Tag]) -> None

Register a liquid tag with the environment.

Built-in tags are registered for you automatically with every new Environment.

PARAMETER DESCRIPTION
tag

The tag to register.

TYPE: Type[Tag]

analyze_tags

analyze_tags(
    name: str,
    *,
    context: Optional["Context"] = None,
    inner_tags: Optional[InnerTagMap] = None,
    **kwargs: str
) -> TagAnalysis

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.

PARAMETER DESCRIPTION
name

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.

TYPE: str

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.

TYPE: Optional['Context'] DEFAULT: None

inner_tags

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.

TYPE: Optional[InnerTagMap] DEFAULT: None

kwargs

Loader context.

TYPE: str DEFAULT: {}

analyze_tags_async async

analyze_tags_async(
    name: str,
    *,
    context: Optional["Context"] = None,
    inner_tags: Optional[InnerTagMap] = None,
    **kwargs: str
) -> TagAnalysis

An async version of Environment.analyze_tags.

analyze_tags_from_string

analyze_tags_from_string(
    source: str,
    name: str = "<string>",
    *,
    inner_tags: Optional[InnerTagMap] = None
) -> TagAnalysis

Analyze tags in template source text.

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.

PARAMETER DESCRIPTION
source

The source text of the template.

TYPE: str

name

A name or identifier for the template.

TYPE: str DEFAULT: '<string>'

inner_tags

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.

TYPE: Optional[InnerTagMap] DEFAULT: None

error

error(
    exc: Union[Type[Error], Error],
    msg: Optional[str] = None,
    linenum: Optional[int] = None,
) -> None

Raise, warn or ignore the given exception according to the current mode.

from_string

from_string(
    source: str,
    name: str = "",
    path: Optional[Union[str, Path]] = None,
    globals: Optional[Mapping[str, object]] = None,
    matter: Optional[Mapping[str, object]] = None,
) -> BoundTemplate

Parse the given string as a liquid template.

PARAMETER DESCRIPTION
source

The liquid template source code.

TYPE: str

name

Optional name of the template. Available as Template.name.

TYPE: str DEFAULT: ''

path

Optional path or identifier to the origin of the template.

TYPE: Optional[Union[str, Path]] DEFAULT: None

globals

An optional mapping of render context variables attached to the resulting template.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

matter

Optional mapping of render context variables associated with the template. Could be "front matter" or other meta data.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

get_template

get_template(
    name: str,
    globals: Optional[Mapping[str, object]] = None,
) -> BoundTemplate

Load and parse a template using the configured loader.

PARAMETER DESCRIPTION
name

The template's name. The loader is responsible for interpreting the name. It could be the name of a file or some other identifier.

TYPE: str

globals

A mapping of render context variables attached to the resulting template.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

RAISES DESCRIPTION
TemplateNotFound

If a template with the given name can not be found.

get_template_async async

get_template_async(
    name: str,
    globals: Optional[Mapping[str, object]] = None,
) -> BoundTemplate

An async version of get_template.

get_template_with_args

get_template_with_args(
    name: str,
    globals: Optional[Mapping[str, object]] = None,
    **kwargs: object
) -> BoundTemplate

Load and parse a template with arbitrary loader arguments.

This method bypasses the environment's template cache. You should use a caching loader instead when the loader requires extra keyword arguments.

New in version 1.9.0.

get_template_with_args_async async

get_template_with_args_async(
    name: str,
    globals: Optional[Mapping[str, object]] = None,
    **kwargs: object
) -> BoundTemplate

An async version of get_template_with_args.

New in version 1.9.0.

get_template_with_context

get_template_with_context(
    context: "Context", name: str, **kwargs: str
) -> BoundTemplate

Load and parse a template with reference to a render context.

This method bypasses the environment's template cache. You should consider using a caching loader.

get_template_with_context_async async

get_template_with_context_async(
    context: "Context", name: str, **kwargs: str
) -> BoundTemplate

An async version of get_template_with_context.

make_globals

make_globals(
    globals: Optional[Mapping[str, object]] = None
) -> Dict[str, object]

Combine environment globals with template globals.

parse

parse(source: str) -> ast.ParseTree

Parse source as a Liquid template.

More often than not you'll want to use Environment.from_string instead.

set_expression_cache_size

set_expression_cache_size(maxsize: int = 0) -> None

Create or replace cached versions of the common expression parsers.

If maxsize is less than 1, no expression caching will happen.

PARAMETER DESCRIPTION
maxsize

The maximum size of each expression cache.

TYPE: int DEFAULT: 0

setup_tags_and_filters

setup_tags_and_filters() -> None

Add default tags and filters to this environment.

tokenizer

tokenizer() -> Callable[[str], Iterator[Token]]

Return a tokenizer for this environment.

Template

Template(
    source: str,
    tag_start_string: str = "{%",
    tag_end_string: str = "%}",
    statement_start_string: str = "{{",
    statement_end_string: str = "}}",
    strip_tags: bool = False,
    tolerance: Mode = Mode.STRICT,
    undefined: Type[Undefined] = Undefined,
    strict_filters: bool = True,
    autoescape: bool = False,
    auto_reload: bool = True,
    cache_size: int = 300,
    globals: Optional[Mapping[str, object]] = None,
    template_comments: bool = False,
    comment_start_string: str = "{#",
    comment_end_string: str = "#}",
    expression_cache_size: int = 0,
) -> BoundTemplate

Parse a template, 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.

PARAMETER DESCRIPTION
tag_start_string

The sequence of characters indicating the start of a liquid tag.

TYPE: str DEFAULT: '{%'

tag_end_string

The sequence of characters indicating the end of a liquid tag.

TYPE: str DEFAULT: '%}'

statement_start_string

The sequence of characters indicating the start of an output statement.

TYPE: str DEFAULT: '{{'

statement_end_string

The sequence of characters indicating the end of an output statement.

TYPE: str DEFAULT: '}}'

strip_tags

Has no effect. We don't support automatic whitespace stripping.

TYPE: bool DEFAULT: False

template_comments

If True, enable template comments, where, by default, anything between {# and #} is considered a comment.

TYPE: bool DEFAULT: False

comment_start_string

The sequence of characters indicating the start of a comment. template_comments must be True for comment_start_string to have any effect.

TYPE: str DEFAULT: '{#'

comment_end_string

The sequence of characters indicating the end of a comment. template_comments must be True for comment_end_string to have any effect.

TYPE: str DEFAULT: '#}'

tolerance

Indicates how tolerant to be of errors. Must be one of Mode.LAX, Mode.WARN or Mode.STRICT.

TYPE: Mode DEFAULT: STRICT

undefined

A subclass of Undefined that represents undefined values. Could be one of the built-in undefined types, Undefined, DebugUndefined or StrictUndefined.

TYPE: Type[Undefined] DEFAULT: Undefined

strict_filters

If True, will raise an exception upon finding an undefined filter. Otherwise undefined filters are silently ignored.

TYPE: bool DEFAULT: True

autoescape

If True, all render context values will be HTML-escaped before output unless they've been explicitly marked as "safe". Requires the package Markupsafe.

TYPE: bool DEFAULT: False

auto_reload

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.

TYPE: bool DEFAULT: True

cache_size

The capacity of the template cache in number of templates. If cache_size is None or less than 1, it has the effect of setting auto_reload to False.

TYPE: int DEFAULT: 300

expression_cache_size

The capacity of each of the common expression caches. A cache_size of 0 will disabling expression caching.

TYPE: int DEFAULT: 0

globals

An optional mapping that will be added to the render context of any template loaded from this environment.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

BoundTemplate

BoundTemplate(
    env: Environment,
    parse_tree: ParseTree,
    name: str = "",
    path: Optional[Union[str, Path]] = None,
    globals: Optional[Dict[str, object]] = None,
    matter: Optional[Mapping[str, object]] = None,
    uptodate: 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.

PARAMETER DESCRIPTION
env

The environment this template is bound to.

TYPE: Environment

parse_tree

The parse tree representing this template.

TYPE: ParseTree

name

Optional name of the template. Defaults to an empty string.

TYPE: str DEFAULT: ''

path

Optional origin path or identifier for the template.

TYPE: Optional[Union[str, Path]] DEFAULT: None

globals

An optional mapping of context variables made available every time the resulting template is rendered. Defaults to None.

TYPE: Optional[Dict[str, object]] DEFAULT: None

matter

Optional mapping containing variables associated with the template. Could be "front matter" or other meta data.

TYPE: Optional[Mapping[str, object]] DEFAULT: None

uptodate

Optional callable that will return True if the template is up to date, or False if it needs to be reloaded. Defaults to None.

TYPE: UpToDate DEFAULT: None

is_up_to_date property

is_up_to_date: bool

False if the template has bee modified, True otherwise.

analyze

analyze(
    follow_partials: bool = True,
    raise_for_failures: bool = True,
) -> TemplateAnalysis

Statically analyze this template and any included/rendered templates.

PARAMETER DESCRIPTION
follow_partials

If True, we will try to load partial templates and analyze those templates too.

TYPE: bool DEFAULT: True

raise_for_failures

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.

TYPE: bool DEFAULT: True

analyze_async async

analyze_async(
    follow_partials: bool = True,
    raise_for_failures: bool = True,
) -> TemplateAnalysis

An async version of analyze.

analyze_with_context

analyze_with_context(
    *args: Any, **kwargs: Any
) -> ContextualTemplateAnalysis

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.

analyze_with_context_async async

analyze_with_context_async(
    *args: Any, **kwargs: Any
) -> ContextualTemplateAnalysis

An async version of analyze_with_context.

is_up_to_date_async async

is_up_to_date_async() -> bool

An async version of the is_up_to_date property.

If template.uptodate is a coroutine, it wil be awaited. Otherwise it will be called just like is_up_to_date

make_globals

make_globals(
    render_args: Mapping[str, object]
) -> Mapping[str, object]

Return a mapping including render arguments and template globals.

make_partial_namespace

make_partial_namespace(
    partial: bool, render_args: Mapping[str, object]
) -> Mapping[str, object]

Return a namespace dictionary.

This is used by render_with_context to extend an existing context.

render

render(*args: Any, **kwargs: Any) -> str

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

Accepts the same arguments as the dict constructor.

render_async async

render_async(*args: Any, **kwargs: Any) -> str

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

render_with_context

render_with_context(
    context: Context,
    buffer: TextIO,
    *args: Any,
    partial: bool = False,
    block_scope: bool = False,
    **kwargs: Any
) -> None

Render the template using an existing context and output buffer.

PARAMETER DESCRIPTION
context

A render context.

TYPE: Context

buffer

File-like object to which rendered text is written.

TYPE: TextIO

partial

If True, indicates that the current template has been included using either a "render" or "include" tag. Defaults to False.

TYPE: bool DEFAULT: False

block_scope

If True, indicates that assigns, breaks and continues from this template will not leak into the parent context. Defaults to False.

TYPE: bool DEFAULT: False

args

Passed to the dict constructor. The resulting dictionary is added to the render context.

TYPE: Any DEFAULT: ()

kwargs

Passed to the dict constructor. The resulting dictionary is added to the render context.

TYPE: Any DEFAULT: {}

render_with_context_async async

render_with_context_async(
    context: Context,
    buffer: TextIO,
    *args: Any,
    partial: bool = False,
    block_scope: bool = False,
    **kwargs: Any
) -> None

An async version of render_with_context.