Skip to content

Environment

liquid.Environment

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
extra

If True, register all extra tags and filters. Defaults to False.

TYPE: bool DEFAULT: False

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".

TYPE: bool DEFAULT: False

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

context_depth_limit class-attribute

context_depth_limit: int = 30

The maximum number of times a render context can be extended or wrapped before raising a ContextDepthError.

filters instance-attribute

filters: dict[str, Callable[..., Any]] = {}

The environment's filter register, mapping filter names to callables.

keyword_assignment class-attribute instance-attribute

keyword_assignment: bool = False

When True accept = or : as the separator token between argument names and argument values. By default only : is allowed.

local_namespace_limit class-attribute

local_namespace_limit: Optional[int] = None

The maximum number of bytes (according to sys.getsizeof) allowed in a template's local namespace before a LocalNamespaceLimitError is raised. We only count the size of the namespaces values, not the size of keys/names.

logical_not_operator class-attribute instance-attribute

logical_not_operator: bool = False

When True, allow the use of the logical not operator in logical expressions. Defaults to False.

logical_parentheses class-attribute instance-attribute

logical_parentheses: bool = False

When True, allow the use of parentheses in logical expressions to group terms. Defaults to False.

loop_iteration_limit class-attribute

loop_iteration_limit: Optional[int] = None

The maximum number of loop iterations allowed before a LoopIterationLimitError is raised.

output_stream_limit class-attribute

output_stream_limit: Optional[int] = None

The maximum number of bytes that can be written to a template's output stream before raising an OutputStreamLimitError.

shorthand_indexes class-attribute instance-attribute

shorthand_indexes: bool = False

When True, accept indexes without enclosing square brackets in paths to variables. Defaults to False.

string_first_and_last class-attribute instance-attribute

string_first_and_last: bool = False

When True, the special first and last properties will return the first and last charters of a string. Otherwise first and last will resolve to Undefined when applied to a string. Defaults to False.

string_sequences class-attribute instance-attribute

string_sequences: bool = False

When True, strings are treated as sequences. That is, characters (Unicode code points) in a string can be looped over and selected by index. Defaults to False.

suppress_blank_control_flow_blocks class-attribute instance-attribute

suppress_blank_control_flow_blocks: bool = True

When True, don't render control flow blocks that contain only whitespace.

tags instance-attribute

tags: dict[str, Tag] = {}

The environment's tag register, mapping tag names to instances of Tag.

template_class class-attribute instance-attribute

template_class: Type[BoundTemplate] = BoundTemplate

Instances of template_class are returned from from_string, get_template and get_template_async. It should be the BoundTemplate class or a subclass of it.

ternary_expressions class-attribute instance-attribute

ternary_expressions: bool = False

When True, allow the use of ternary expression in output statements, assign tags and echo tags. Defaults to False.

_parse

_parse(source: str) -> list[Node]

Parse source as a Liquid template.

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

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["RenderContext"] = 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['RenderContext'] 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["RenderContext"] = 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[LiquidError], LiquidError],
    msg: Optional[str] = None,
    token: Optional[Token] = 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: Mapping[str, object] | None = None,
    context: RenderContext | None = None,
    **kwargs: object
) -> 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: Mapping[str, object] | None DEFAULT: None

context

An optional render context that can be used to narrow the template source search space.

TYPE: RenderContext | None DEFAULT: None

kwargs

Arbitrary arguments that can be used to narrow the template source search space.

TYPE: object DEFAULT: {}

RAISES DESCRIPTION
TemplateNotFound

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

get_template_async async

get_template_async(
    name: str,
    *,
    globals: Mapping[str, object] | None = None,
    context: RenderContext | None = None,
    **kwargs: object
) -> BoundTemplate

An async version of get_template().

make_globals

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

Combine environment globals with template globals.

parse

parse(
    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

render

render(source: str, **data: object) -> str

Parse and render source text.

render_async async

render_async(source: str, **data: object) -> str

Parse and render source text.

setup_tags_and_filters

setup_tags_and_filters(*, extra: bool = False) -> None

Add default tags and filters to this environment.

If extra is True, register all extra, non-standard tags and filters too.

tokenizer

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

Return a tokenizer for this environment.