If statement in HTML Template in Python Flask

Flask – If statement in HTML template

In a flask application, we can write If statement in HTML template.

Flask is bundled with Jinja2 language. This enables us to include variables, If statements, or Loop statements in the HTML template.

In this tutorial, we will learn how to write an If statement in HTML template, in a Python flask application.

The following is a simple code snippet to write If statement in HTML template.

{% if username == "": %}
<!--if block html code-->
{% else %}
<!--else block html code-->
{% endif %}

where if, else, endif are keywords, and also colon symbol : after if-condition is part of syntax. Also, please observe that the code is enclosed in braces and percentile symbols.

You can write as many number of HTML lines as required in if-block or else-block.


In this example, flask application, we will write an if-statement in HTML template index.html. Based on the value of username query parameter, we will display respective Heading 1 in HTML.

Consider a flask application with the following project structure.

Python flask project structure


from flask import Flask, render_template, request

app = Flask(__name__)

def home_page():
    username = request.args['username']
    return render_template("index.html", username=username)

if __name__ == "__main__":
    app.run(host="", port=8080, debug=True)

We read the value for URL parameter 'username' using the expression request.args['username'], pass it to the HTML template, and use this value in the condition of if-statement.


<!DOCTYPE html>
  {% if username == "": %}
  <h1>Hello User!</h1>
	{% else %}
  <h1>Hello {{ username }}!</h1>
	{% endif %}
	<p>Welcome to sample flask application by <a href="https://pythonexamples.org/">PythonExamples.org</a>.</p>

Run Application

Open terminal or command prompt at the root of the flask application, and run the Python file main.py.

Run Flask Application

The flask application is up and running at URL

Now, open a browser of your choice and hit the URL Since there is a value passed to username, based on the condition, else-block must execute.

Now, open a browser of your choice and hit the URL Since there is no value passed to username, based on the condition, if-block must execute.

Based on the condition evaluation, if block or else block has been executed.

Project ZIP


In this Python Tutorial, we learned how to write an If-statement in HTML template, with the help of an example flask application.