Flask Template Conditions
A template condition shows a block only when a test passes. The {% if %} line starts the condition.
Make the app
This line imports Flask and render_template_string together. The routes below render one shared template.
from flask import Flask, render_template_string
app = Flask(__name__)The member page
This route passes member=True, so the first block shows.
@app.route("/member")
def member():
return render_template_string("{% if member %}<p>Welcome back!</p>{% else %}<p>Please join.</p>{% endif %}", member=True)The guest page
This route passes member=False, so the else block shows instead.
@app.route("/guest")
def guest():
return render_template_string("{% if member %}<p>Welcome back!</p>{% else %}<p>Please join.</p>{% endif %}", member=False)Ask for both pages
The test client asks for each address and prints the page each reader sees.
client = app.test_client()
print(client.get("/member").data.decode())
print(client.get("/guest").data.decode())Example
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/member")
def member():
return render_template_string("{% if member %}<p>Welcome back!</p>{% else %}<p>Please join.</p>{% endif %}", member=True)
@app.route("/guest")
def guest():
return render_template_string("{% if member %}<p>Welcome back!</p>{% else %}<p>Please join.</p>{% endif %}", member=False)
client = app.test_client()
print(client.get("/member").data.decode())
print(client.get("/guest").data.decode())Key points
- {% if member %} shows the block when member is true.
- {% else %} shows the other block when the test fails.
- The block ends with {% endif %}.
- Conditions hide parts of a page for some readers.
In this example, both routes render the same template with a different member value. The /member route passes True, so the page says "Welcome back!". The /guest route passes False, so the page says "Please join.". The test client asks for both and prints each page.
Note
The test uses the value passed to the template.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does {% if member %} show when member is False?