Static analysis¶
Instances of liquid.Template returned from liquid.parse(),
liquid.Environment.parse() and liquid.Environment.get_template() include
methods for inspecting template variable, tag and filter usage without rendering the
template.
Variables¶
liquid.Template.variables() and liquid.Template.variables_async() return a
list of variables used in the template, without path segments. The list will include
variables that are local to the template (like those created with {% assign %}) and
block scoped variables (like forloop).
from liquid import parse
source = """\
Hello, {{ you }}!
{% assign x = 'foo' | upcase %}
{% for ch in x %}
- {{ ch }}
{% endfor %}
Goodbye, {{ you.first_name | capitalize }} {{ you.last_name }}
Goodbye, {{ you.first_name }} {{ you.last_name }}
"""
template = parse(source)
print(template.variables())
# ['you', 'x', 'ch']
Paths¶
liquid.Template.variable_paths() and liquid.Template.variable_paths_async()
return a list of variables used in the template with their path segments.
# ... continued from above
print(template.variable_paths())
# ['you.last_name', 'you', 'ch', 'you.first_name', 'x']
Segments¶
liquid.Template.variable_segments() and liquid.Template.variable_segments_async()
return a list of variables used in the template with their path segments as nested tuples.
# ... continued from above
print(template.variable_segments())
# [('you', 'last_name'), ('ch',), ('you', 'first_name'), ('x',), ('you',)]
Global variables¶
liquid.Template.global_variables(), liquid.Template.global_variable_paths(),
and liquid.Template.global_variable_segments() (and their async equivalents) are
similar to the methods described above, but exclude local and block scoped variables.
# ... continued from above
print(template.global_variables())
# ['you.last_name', 'you', 'ch', 'you.first_name', 'x']
print(template.global_variable_paths())
# ['you', 'you.first_name', 'you.last_name']
print(template.global_variable_segments())
# [('you',), ('you', 'last_name'), ('you', 'first_name')]
Errors¶
liquid.Template.errors() returns a list of ErrorNode and ErrorExpr instances.
Both have error properties containing a liquid.exceptions.LiquidSyntaxError,
and a human readable string representation.
Note that errors will only be populated when using Lax parsing. Otherwise an
exception will have been raised before you get a Template instance.
from liquid import Environment, LaxLegacyParser
env = Environment(parser=LaxLegacyParser)
template = env.parse("{% if a b %}TRUE{% else %}FALSE{% endif %}")
for err in template.errors():
print(err)
Comments and docs¶
liquid.Template.comments()andliquid.Template.docs()return lists of comment andDocTagnodes, respectively. All comment and doc nodes havetokenandtextproperties.