Escaping in Flask Templates
Escaping keeps typed text safe in a page. Flask turns < and > into harmless codes by default.
Make the app
This line imports Flask and render_template_string together. The routes below render one value two ways.
from flask import Flask, render_template_string
app = Flask(__name__)Escaped by default
The template shows the value as text. The <b> tags turn into harmless codes.
@app.route("/safe")
def safe():
return render_template_string("<p>{{ text }}</p>", text="<b>bold</b>")Raw with |safe
The |safe filter turns escaping off. The same value now renders as bold HTML.
@app.route("/raw")
def raw():
return render_template_string("<p>{{ text|safe }}</p>", text="<b>bold</b>")Ask for both pages
The test client asks for each address. The prints show the escaped page and the raw page side by side.
client = app.test_client()
print(client.get("/safe").data.decode())
print(client.get("/raw").data.decode())Example
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/safe")
def safe():
return render_template_string("<p>{{ text }}</p>", text="<b>bold</b>")
@app.route("/raw")
def raw():
return render_template_string("<p>{{ text|safe }}</p>", text="<b>bold</b>")
client = app.test_client()
print(client.get("/safe").data.decode())
print(client.get("/raw").data.decode())Key points
- {{ text }} escapes < and > in the value.
- Escaped text shows as text, never as HTML.
- The |safe filter turns escaping off for one value.
- Use |safe only for HTML the app itself wrote.
In this example, both routes render the same value, <b>bold</b>. The /safe route escapes it, so the page shows the tags as text. The /raw route uses |safe, so the page renders bold HTML. The test client asks for both and prints each page.
Note
Escaping guards against typed HTML from strangers.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does {{ text }} show for the value "<b>bold</b>"?