HTML Auto-Escape
Python Liquid offers HTML auto-escaping. Where render context variables are automatically escaped on output. Install optional dependencies for auto-escaping using the autoescape
extra.
$ pipenv install python-liquid[autoescape]
Or
$ python -m pip install -U python-liquid[autoescape]
Auto-escaping is disabled by default. Enable it by setting the Environment
or Template
autoescape
argument to True
.
from liquid import Environment
env = Environment(autoescape=True)
template = env.from_string("<p>Hello, {{ you }}</p>")
print(template.render(you='</p><script>alert("XSS!");</script>'))
output
<p>Hello, </p><script>alert("XSS!");</script></p>
Markup
Mark a string as "safe" by wrapping it in a Markup
object.
from liquid import Environment, Markup
env = Environment(autoescape=True)
template = env.from_string("<p>Hello, {{ you }}</p>")
print(template.render(you=Markup("<em>World!</em>")))
'<p>Hello, <em>World!</em></p>'
Safe
Alternatively use the non-standard safe filter.
caution
The safe
filter is not available in "standard" Liquid.
from liquid import Environment
env = Environment(autoescape=True)
template = env.from_string("<p>Hello, {{ you | safe }}</p>")
print(template.render(you="<em>World!</em>"))
'<p>Hello, <em>World!</em></p>'