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.

Example

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

main.py

from flask import Flask, render_template, request

app = Flask(__name__)

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

if __name__ == "__main__":
    app.run(host="127.0.0.1", 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.

index.html

<!DOCTYPE html>
<html>
  <body>
  {% 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>
  </body>
</html>

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 http://127.0.0.1:8080/.

Now, open a browser of your choice and hit the URL http://127.0.0.1:8080/?username=Tony. Since there is a value passed to username, based on the condition, else-block must execute.

If statement in HTML Template in Python Flask

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

If statement in HTML Template in Python Flask

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

Project ZIP

Summary

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

Related Tutorials

Code copied to clipboard successfully 👍