External Exam Download Resources Web Applications Games Recycle Bin

Using 'is (not) defined' for safety in Jinja2

j2_defined.py

from flask import *
import random

app = 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

<p>Welcome to ticket central, try <a href="/">re-routing the page</a> a few times.</p>

{% if promotion is defined %}
  <p>Concert promotion: <a href="/tswift">Tay Tay</a> or <a href="/beibs">Beiber</a></p>
{% elif promotion is not defined and singer is not defined %}
  <p>No promotions.</p>
{% else %}
  <p>Tickets have been issued.</p>
{% endif %}

{% if singer is defined %}
  {% if singer == "beiber" %}
    <p>Have fun at the Justin Beiber concert!</p>
  {% else %}
    <p>Have fun at the Taylor Swift concert!</p>
  {% endif %}
{% endif %}