Using 'is (not) defined' for safety in Jinja2
j2_defined.py
from flask import *import randomapp = Flask(__name__)@app.route("/")def main():if random.randint(1, 2) == 1:return render_template("routing.html", promotion="concert")else:return render_template("routing.html")@app.route("/beibs")def belieber():return render_template("routing.html", singer="beiber")@app.route("/tswift")def swifty():return render_template("routing.html", singer="tswift")app.run(debug=True)
templates\routing.html
Welcome to ticket central, try href="/"re-routing the page a few times.{% if promotion is defined %}Concert promotion: href="/tswift"Tay Tay or href="/beibs"Beiber{% elif promotion is not defined and singer is not defined %}No promotions.{% else %}Tickets have been issued.{% endif %}{% if singer is defined %}{% if singer == "beiber" %}Have fun at the Justin Beiber concert!{% else %}Have fun at the Taylor Swift concert!{% endif %}{% endif %}