1. Creating a Web Page (HTML) Using Python Flask¶
1.1. Jinja2 Template¶
- A simple syntax used when parts of a webpage need to be dynamically modified.
- Enables Python programming directly in the webpage.
- While Jinja2 offers detailed functionality, focus on the core concepts when starting.
- The two key syntaxes are:
{{ variable_name }}
{% Python code %}
1.2. Jinja2 Template Engine¶
- The Jinja2 template engine takes the HTML code and converts it into a template.
- Python code within the template is executed to fill the template, generating the final HTML file.
1.3. Variables (Jinja2 Template Syntax)¶
- Variables can be dynamically inserted into the HTML using the
{{ variable_name }}
syntax.
1.4. Folder Structure¶
The following folder structure is used to organize the Flask project:
/variable_test.py
/templates
/variable.html
2. Testing Variable Rendering in variable.html
¶
- The
render_template()
function is used to pass variable values into the template for rendering.
2.1. variable.html
¶
- In the HTML template, specify where the variable values will be inserted using the
{{ variable_name }}
syntax.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>Hello {{ name }}</h1> <!-- 'name' variable will be dynamically inserted here -->
</body>
</html>
In [1]:
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/hello/<user>')
def hello_name(user):
# Pass the 'user' variable to the HTML template
return render_template('variable.html', name=user)
if __name__ == '__main__':
app.run(host="127.0.0.1", port="5555")
* Serving Flask app '__main__' * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5555 Press CTRL+C to quit 127.0.0.1 - - [02/Jan/2025 22:25:00] "GET /hello/kim HTTP/1.1" 200 -
['login.html', 'login_bootstrap.html', 'variable.html']
3. Loops in Jinja2 Template Syntax¶
3.1. Folder Structure¶
Organize the project files as follows:
/loop_test.py
/templates
/loop.html
3.2. Loop Syntax in Jinja2 Templates¶
- The basic syntax for a loop is to use
for
to declare the loop andendfor
to end it.
{% for %} {% endfor %}
- Example:
- Indentation is not required but is often used for readability.
{% for value in values %}
{{ value }}
{% endfor %}
In [ ]:
### Flask Code Example
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/loop')
def loop():
# A list of values to pass to the template
value_list = ['item1', 'item2', 'item3']
return render_template('loop.html', values=value_list)
if __name__ == '__main__':
app.run(host="0.0.0.0", port="5555")
3.3. HTML Template: loop.html
¶
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<ul>
<!-- Loop through the 'values' list and display each item in an <li> -->
{% for value in values %}
<li>{{ value }}</li>
{% endfor %}
</ul>
</body>
</html>
3.4. Advanced Loop Syntax in Jinja2¶
Jinja2 provides additional functionality for working with loops, but it has some differences compared to regular Python loops. Here's an explanation of these features:
range()
- Similar to Python's
range()
:- You can use
range()
in Jinja2, but it must work with thelength
filter for iterable objects like lists. - Note:
for index in range(len(values))
is not valid in Jinja2.
- You can use
len(values)
- In Jinja2, to get the length of a list (like Python's
len()
), you need to use:values | length
- The
| length
is a Jinja2 filter that returns the number of elements in a list.
- The
loop.index
- Retrieve the Current Iteration Count:
- Use
loop.index
inside the loop to get the current iteration number (1-based index). - Example:
- For a list of
values = ['list1', 'list2', 'list3']
, the output ofloop.index
will be:1, 2, 3
- For a list of
- Use
value[index]
- Access a List Element by Index:
- Works the same way as Python's list indexing.
- Example:
values[index]
retrieves the element at positionindex
from the list.
3.5. Example: Jinja2 Loop in HTML¶
Here's an example of using advanced loop functionality:
<ul>
<!-- Use range() and loop.index to iterate through the list -->
{% for index in range(values | length) %}
<li>{{ values[index] }} {{ loop.index }}</li>
{% endfor %}
</ul>
3.6. Explanation of the Example:¶
range(values | length)
:- Iterates over the range of the list length (
values | length
).
- Iterates over the range of the list length (
values[index]
:- Dynamically accesses the element at the
index
position in the list.
- Dynamically accesses the element at the
loop.index
:- Provides the current iteration count (starting from 1).
3.7. Sample Output:¶
If values = ['list1', 'list2', 'list3']
, the generated HTML would look like:
<ul>
<li>list1 1</li>
<li>list2 2</li>
<li>list3 3</li>
</ul>
4. Conditionals in Jinja2 Template Syntax¶
4.1. Folder Structure¶
The folder structure for this example should be as follows:
/condition_test.py
/templates
/condition.html
4.2. Conditional Statements in Jinja2 Templates¶
- Jinja2 supports
if
,elif
,else
, andendif
for conditional logic. elif
andelse
are optional depending on your use case.
Basic Syntax:
{% if %} {% elif %} {% else %} {% endif %}
Example:
- Indentation is not required but improves readability.
{% if data >= 30 %}
<h3>The value is greater than or equal to 30.</h3>
{% elif data > 25 %}
<h3>The value is greater than 25.</h3>
{% else %}
<h3>{{ data }}</h3>
{% endif %}
In [2]:
### Flask Code Example
from flask import Flask, render_template
app = Flask(__name__)
@app.route('/condition/<int:value>')
def condition(value):
# Pass a value (27 in this case) to the HTML template
return render_template('condition.html', data=value)
if __name__ == "__main__":
app.run(host="127.0.0.1", port="5555")
* Serving Flask app '__main__' * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5555 Press CTRL+C to quit 127.0.0.1 - - [02/Jan/2025 22:42:18] "GET /condition/26 HTTP/1.1" 200 - 127.0.0.1 - - [02/Jan/2025 22:42:52] "GET /condition/30 HTTP/1.1" 200 -
4.3. HTML Template: condition.html
¶
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Condition Example</title>
</head>
<body>
<!-- Render different content based on the value of 'data' -->
{% if data >= 30 %}
<h3>The value is greater than or equal to 30.</h3>
{% elif data > 25 %}
<h3>The value is greater than 25.</h3>
{% else %}
<h3>{{ data }}</h3>
{% endif %}
</body>
</html>
4.4. Explanation:¶
Jinja2 Conditionals:
if
checks the condition (data >= 30
).elif
adds an additional condition (data > 25
).else
handles all other cases when neitherif
norelif
are satisfied.
Flask Code:
- The
hello_html()
function sets the value ofdata
to 27 and passes it to thecondition.html
template.
- The
Rendered Output in Browser:
- When you visit
http://0.0.0.0:8080/hello_if
in the browser, the conditiondata > 25
is true. - The browser will display:
<h3>The value is greater than 25.</h3>
- When you visit